SQL SQL中的逗号分隔列表

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10031658/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-01 15:12:51  来源:igfitidea点击:

Comma separated list in SQL

sqlsql-serversql-server-2008

提问by Virus

How to loop through comma separated list in SQL? I have a list of ID's and I need to pass these ID's to a stored procedure. I CANNOT alter the stored procedure. I need to figure out how to execute the SP for each id. Give me some ideas, I can carry on from there.

如何遍历 SQL 中的逗号分隔列表?我有一个 ID 列表,我需要将这些 ID 传递给存储过程。我不能改变存储过程。我需要弄清楚如何为每个 id 执行 SP。给我一些想法,我可以从那里继续。

Thanks.

谢谢。

回答by Mikael Eriksson

declare @S varchar(20)
set @S = '1,2,3,4,5'

while len(@S) > 0
begin
  --print left(@S, charindex(',', @S+',')-1)
  exec YourSP left(@S, charindex(',', @S+',')-1)
  set @S = stuff(@S, 1, charindex(',', @S+','), '')
end

Try on SE Data: Walk the string

试用 SE 数据:走字符串