好吧,我一直使用的解决方案,可能还有更好的方法,就是使用一个可以拆分所有内容的函数。没有使用游标,只是一个while循环。
if OBJECT_ID('splitValueByDelimiter') is not null
begin
drop function splitValueByDelimiter
end
go
create function splitValueByDelimiter (
@inputValue varchar(max)
, @delimiter varchar(1)
)
returns @results table (value varchar(max))
as
begin
declare @delimeterIndex int
, @tempValue varchar(max)
set @delimeterIndex = 1
while @delimeterIndex > 0 and len(isnull(@inputValue, '')) > 0
begin
set @delimeterIndex = charindex(@delimiter, @inputValue)
if @delimeterIndex > 0
set @tempValue = left(@inputValue, @delimeterIndex - 1)
else
set @tempValue = @inputValue
if(len(@tempValue)>0)
begin
insert
into @results
select @tempValue
end
set @inputValue = right(@inputValue, len(@inputValue) - @delimeterIndex)
end
return
end
之后,您可以像这样调用输出:
if object_id('test') is not null
begin
drop table test
end
go
create table test (
Id varchar(max)
)
insert
into test
select '10031,10042'
union all select '10064,10023,10060,10065,10003,10011,10009,10012,10027,10004,10037,10039'
union all select '10009'
union all select '20011,10027,10032,10063,10023,10033,20060,10012,10020,10031,10011,20036,10041'
select value
from test
cross apply splitValueByDelimiter(Id, ',')
希望它有所帮助,尽管我仍在遍历所有内容