开发者

Suggest some alternatives to an intensive CURSOR operation in SQL Server 2005

I am iterating through a dataset of products looking for SKUs where the initial 6 characters of th开发者_Go百科e product name with the sku @itemno are identical, then concatenating them into a CSV string to be used as part of a dataset to upload into an ecommerce platform. Here is the relevant operation:

DECLARE c1 CURSOR READ_ONLY
FOR
SELECT sku FROM tbl WHERE name LIKE (SELECT LEFT(name,6) FROM tbl WHERE sku = @itemno) + '%'

OPEN c1
FETCH NEXT FROM c1
INTO @c1
WHILE @@FETCH_STATUS = 0
BEGIN
    SET @associated = @associated + @c1 + ','
    FETCH NEXT FROM c1
    INTO @c1
END

As you can imagine this is very slow considering the dataset size of 15,000+ records. Surely there is a more elegant way to do this using PIVOT or something?


SQL Server 2005 onwards:

select 
  stuff( 
     (select ', ' + sku  
     from tbl 
     WHERE name LIKE (SELECT LEFT(name,6) FROM tbl WHERE sku = @itemno) + '%' 
     for xml path('') 
     ) 
   , 1, 2, '') as namelist;


Try something like

DECLARE @Val VARCHAR(MAX)
SELECT  @Val = COALESCE(@Val + ',','') + sku 
FROM    tbl 
WHERE   name LIKE   (
                        SELECT  LEFT(name,6) 
                        FROM    tbl 
                        WHERE   sku = @itemno) + '%'
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜