我有3个存储过程参数,如
@String1 varchar(100) = 'a,b,c';
@String2 Varchar(100) = '1,2,3';
@String3 Varchar(100) = 'x,y,z';
我需要拆分这些数据并将其作为
插入到表中column1 column2 column3
------- -------- ----------
a 1 x
b 2 y
c 3 z
答案 0 :(得分:1)
我已经有一个函数将分离的sting分成结果集(见下文)
create function [dbo].[SplitStringToResultSet] (@value varchar(max), @separator char(1))
returns table
as return
with r as (
select value, cast(null as varchar(max)) [x], 0 [no] from (select rtrim(cast(@value as varchar(max))) [value]) as j
union all
select right(value, len(value)-case charindex(@separator, value) when 0 then len(value) else charindex(@separator, value) end) [value]
, left(r.[value], case charindex(@separator, r.value) when 0 then len(r.value) else abs(charindex(@separator, r.[value])-1) end ) [x]
, [no] + 1 [no]
from r where value > '')
select x [value], [no] from r where x is not null
使用此功能可以解决您的问题,例如:
select n1.value [column1], n2.value [column2], n3.value [column3]
from [dbo].[SplitStringToResultSet] ('a,b,c', ',') n1
join [dbo].[SplitStringToResultSet] ('1,2,3', ',') n2 on n1.[no] = n2.[no]
join [dbo].[SplitStringToResultSet] ('x,y,z', ',') n3 on n1.[no] = n3.[no]
结果
column1 column2 column3
a 1 x
b 2 y
c 3 z