遍历我的SQL Server数据库中的所有记录

时间:2012-11-02 14:46:52

标签: sql-server-2008 tsql

我有以下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

1 个答案:

答案 0 :(得分: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