我想在存储过程中更新在字符串逗号分隔列表中传递的ID列表,其中包含以逗号分隔的字符串值列表。
那么如何使用2个列表中的相应名称更新每个ID。 例如:
ids = "1, 2, 4 ,8";
names = "sam, john, sarah ,barry";
ALTER PROCEDURE [dbo].[update_work]
@ids nvarchar(MAX),
@names nvarchar(MAX)
AS
BEGIN
???
END
答案 0 :(得分:1)
正确的方法是使用表值参数。
但是你说你不能这样我会使用SUBSTRING
和tally table来分割逗号分隔的字符串。
结构:
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');
过程(临时过程,因为SEDE不允许创建普通的数据库对象):
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;
测试:
EXEC #update_work
@ids = '1, 2, 4 ,8',
@names = 'sam, john, sarah ,barry';
SELECT *
FROM #tab;
输出:
╔════╦═══════╗
║ id ║ name ║
╠════╬═══════╣
║ 1 ║ sam ║
║ 2 ║ john ║
║ 3 ║ c ║
║ 4 ║ sarah ║
║ 5 ║ e ║
║ 6 ║ f ║
║ 7 ║ g ║
║ 8 ║ barry ║
║ 9 ║ i ║
╚════╩═══════╝