如果您被迫在存储过程中执行此操作并且您的数组大小相等,您可以加入两个列表,拆分它们,然后加入位置(每个数组中的元素数)以获得您需要的链接集。
下面的示例使用数字表,但您可以用任何替换该拆分操作。
-- if you dont have a number table:
/*
create table [dbo].[Number](n int not null primary key clustered);
insert into dbo.Number
values (1),(2),(3),(4),(5),(6),(7),(8),(9),(10),
(11),(12),(13),(14),(15),(16),(17),(18),(19),(20)
*/
declare @lstid varchar(100) = '1,2,3,4,51',
@lstvalue varchar(100) = '10,20,22,35,60'
declare @Length tinyint,
@Input varchar(8000),
@Delimiter char(1)
-- sanity check
if len(@lstid)-len(replace(@lstid, ',', '')) <> len(@lstvalue)-len(replace(@lstvalue, ',', ''))
begin
raiserror('lists are not equal', 16, 1);
return;
end
--count the numbers of elements in one of the arrays
select @Length = len(@lstid)-len(replace(@lstid, ',', ''))+1;
--join the two arrays into one
select @Input = @lstid + ',' + @lstvalue;
set @Delimiter = ',';
;with cte (i,s)
as (
select row_number() over (order by n.n asc) [i],
substring(@Delimiter + @Input + @Delimiter, n.n + 1, charindex(@Delimiter, @Delimiter + @Input + @Delimiter, n.n + 1) - n.n - 1) [s]
from dbo.Number n
where n.n = charindex(@Delimiter, @Delimiter + @Input + @Delimiter, n.n) and
n.n <= len(@Delimiter + @Input)
)
select a.s, b.s
from cte a
join cte b on
a.i+@Length = b.i
order
by a.i;
return