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) + '%'
 
         
                                         
                                         
                                         
                                        ![Interactive visualization of a graph in python [closed]](https://www.devze.com/res/2023/04-10/09/92d32fe8c0d22fb96bd6f6e8b7d1f457.gif) 
                                         
                                         
                                         
                                         加载中,请稍侯......
 加载中,请稍侯......
      
精彩评论