2

I want to update in stored procedure a list of IDs passed in string comma separated list with a string comma separated list of Values.

So How can i update each ID with it's corresponding name from the 2 lists. for example:

ids = "1, 2, 4 ,8";
names = "sam, john, sarah ,barry";

ALTER PROCEDURE [dbo].[update_work]
  @ids nvarchar(MAX),
  @names nvarchar(MAX)
AS
BEGIN
    ???
END
  • 1
    Fix your data structure to store lists in tables rather than strings. – Gordon Linoff Jan 01 '16 at 17:28
  • 1
    I think he is getting the strings passed from UI as a list of User selection . Please check `CROSS APPLY` .More can be found here http://stackoverflow.com/questions/5493510/turning-a-comma-separated-string-into-individual-rows – minatverma Jan 01 '16 at 17:36
  • I'm getting the data from a jQuery UI control so i can't change it, so how can i update each ID with it's corresponding name from the 2 lists. – Khairy Abd El-Zaher Jan 01 '16 at 18:00
  • Use a string splitting function like DelimitedSplit8k and join the data with the item numbers – James Z Jan 01 '16 at 18:51

1 Answers1

1

The correct way is to use table valued parameter.

But you said that you can't so I will use SUBSTRING and tally table to split comma separated string.

Structures:

CREATE TABLE #tab(id INT, name VARCHAR(100));

INSERT INTO #tab(id, name)
VALUES (1, 'a'), (2, 'b'), (3, 'c'), (4, 'd'),
       (5, 'e'), (6, 'f'), (7, 'g'), (8, 'h'), (9, 'i');  

Procedure (temp procedure because SEDE does not allow to create normal database objects):

CREATE PROCEDURE #update_work @ids nvarchar(MAX), @names nvarchar(MAX)
AS
BEGIN
 ;WITH cte AS
 ( SELECT TOP 1000 rn = ROW_NUMBER() OVER(ORDER BY 1/0)
   FROM master..spt_values
 ), cte2 AS
 ( SELECT [val] = SUBSTRING(',' + @ids + ',', rn + 1,
                   CHARINDEX(',', ',' + @ids + ',', rn + 1) - rn -1)
         ,[r] =  ROW_NUMBER() OVER(ORDER BY rn)
         ,[type] = 'id'
  FROM cte
  WHERE rn <= LEN(',' + @ids + ',') - 1
   AND SUBSTRING(',' + @ids + ',', rn, 1) = ','
  UNION ALL 
  SELECT [val] = SUBSTRING(',' + @names + ',', rn + 1,
                   CHARINDEX(',', ',' + @names + ',', rn + 1) - rn -1)
         ,[r] =  ROW_NUMBER() OVER(ORDER BY rn)
         ,[type] = 'name'
  FROM cte
  WHERE rn <= LEN(',' + @names + ',') - 1
   AND SUBSTRING(',' + @names + ',', rn, 1) = ','
 ), cte3 AS
 ( SELECT [id] = cte2.val, [name] = cte2a.val
   FROM cte2
   JOIN cte2 AS cte2a
     ON cte2.[r] = cte2a.[r]
    AND cte2.[type] = 'id'
    AND cte2a.[type] = 'name'
 )
 UPDATE t
 SET name = c3.name
 FROM #tab AS t
 JOIN cte3 c3 ON t.id = c3.id;
END;

Testing:

EXEC #update_work
    @ids = '1, 2, 4 ,8', 
    @names = 'sam, john, sarah ,barry';

SELECT * 
FROM #tab;  

LiveDemo

Output:

╔════╦═══════╗
║ id ║ name  ║
╠════╬═══════╣
║  1 ║ sam   ║
║  2 ║ john  ║
║  3 ║ c     ║
║  4 ║ sarah ║
║  5 ║ e     ║
║  6 ║ f     ║
║  7 ║ g     ║
║  8 ║ barry ║
║  9 ║ i     ║
╚════╩═══════╝
Lukasz Szozda
  • 162,964
  • 23
  • 234
  • 275