【问题标题】:How to get the values of comma delimited string into a table?如何将逗号分隔字符串的值放入表中?
【发布时间】:2015-05-15 14:17:15
【问题描述】:

我在变量中有一个字符串@str =11,22。我怎样才能将它插入到表格中,

 id      num
-------------
 1       11
 2       22

【问题讨论】:

标签: sql sql-server-2008 split


【解决方案1】:

这是一种获取所需内容的简单方法,尽管它取决于用逗号分隔且没有空格的值(但如果您认为可能发生这种情况,您可以使用 trim):

Declare @str varchar(10) = '11,22,33'
Declare @foobar table (id int identity (1,1), num int)

while (CHARINDEX(',', @str) > 0)
begin
insert into @foobar (num)
Select Left(@Str, CHARINDEX(',', @str) - 1)
Set @str = (select SUBSTRING(@str, CHARINDEX(',', @str) + 1, Len(@str)))
end
if Len(@Str) > 0
    insert into @foobar (num) 
    select @str

select * from @foobar

这里是 SQL Fiddle:http://www.sqlfiddle.com/#!6/0e240/2/0

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多