1

我有以下 SQL 脚本。如您所见,我手动将@listingid值设置为 30653。

但是应该对[listings]表中@listingid分配了[listings].id列值的所有记录执行此脚本。

DECLARE @profname nvarchar(150)
DECLARE @furl nvarchar(250)
DECLARE @city nvarchar(250)
DECLARE @listingid int

set @listingid=30653
--select the top 1 professionname
SELECT TOP 1 @profname=REPLACE(LOWER(pn.title),' ','-'),@furl=l.friendlyurl,@city=REPLACE(REPLACE(LOWER(l.city),'''',''),' ','-') FROM healthprof_professionnames hpn
INNER JOIN professionname pn ON pn.id=hpn.professionnameid
INNER JOIN listings l on l.id=hpn.healthprofid
WHERE l.id=@listingid ORDER BY pn.title

--check if current friendlyurl already contains profession
IF NOT CHARINDEX(@profname,@furl)>0
    SET @furl = @furl + '-' + @profname

IF NOT CHARINDEX(@city,@furl)>0
SET @furl = @furl + '-' + @city

SET @furl = @furl + '-3'

UPDATE listings set friendlyurl=@furl WHERE id=@listingid
4

1 回答 1

2

您可以使用游标遍历结果集中的每一行:

declare cur cursor for
select distinct id from listings

declare @listingid int
open cur
fetch next from cur into @listingid 

while @@FETCH_STATUS = 0
BEGIN
    -- your code from above goes here

    fetch next from cur into @listingid 
END

话虽如此,我同意蒂姆的上述评论。如果可能的话,重写它以在一个基于集合的操作中工作。我认为这会起作用,但我还没有测试过:

;WITH vars AS (
    SELECT id, profname, furl, city
    FROM (
        SELECT l.id,
            REPLACE(LOWER(pn.title),' ','-') as profname,
            l.friendlyurl as furl,
            REPLACE(REPLACE(LOWER(l.city),'''',''),' ','-') as city,
            ROW_NUMBER() OVER (PARTITION BY l.id ORDER BY pn.title) as rnk
        FROM healthprof_professionnames hpn
        INNER JOIN professionname pn ON pn.id=hpn.professionnameid
        INNER JOIN listings l on l.id=hpn.healthprofid
    ) A
    WHERE A.rnk = 1
),
vars2 AS (
    SELECT id,
        CASE WHEN NOT CHARINDEX(profname, furl) > 0
            THEN furl + '-' + profname ELSE furl END as furl,
        city
    FROM vars
),
vars3 as (
    SELECT id,
        CASE WHEN NOT CHARINDEX(city, furl) > 0
            THEN furl + '-' + city ELSE furl END as furl
    FROM vars2
)
UPDATE listings SET friendlyurl = vars3.furl + '-3'
FROM listings INNER JOIN vars3 on vars3.id = listings.id
于 2012-11-02T14:50:53.753 回答