开发者

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

开发者 https://www.devze.com 2023-01-31 08:54 出处:网络
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 str

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

精彩评论

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

关注公众号