我们有一个将分隔列表转换为表格的函数:
select * from dbo.fn_rpt_ParseValues('abc|123|test','|')
结果:
abc
123
test
如何将每一行都放入SQL变量?例如:
@Name = 'abc'
@Phone = '123'
@Comment = 'test'
谢谢!
答案 0 :(得分:5)
declare @S varchar(100) = 'abc|123|test'
declare @Name varchar(10)
declare @Phone varchar(10)
declare @Comment varchar(10)
select @Name = X.value('x[1]', 'varchar(10)'),
@Phone = X.value('x[2]', 'varchar(10)'),
@Comment = X.value('x[3]', 'varchar(10)')
from (select cast('<x>'+replace(@S, '|', '</x><x>')+'</x>' as xml)) as T(X)
select @Name, @Phone, @Comment
答案 1 :(得分:1)
DECLARE @Split table(
RowIndex int IDENTITY(1,1)
,Item varchar(200));
INSERT INTO @Split
SELECT * from dbo.fn_rpt_ParseValues('abc|123|test','|');
DECLARE @Name varchar(50);
DECLARE @Phone varchar(50);
DECLARE @Comment varchar(100);
SET @Name = (SELECT Item FROM @Split WHERE RowIndex=1);
SET @Phone = (SELECT Item FROM @Split WHERE RowIndex=2);
SET @Comment = (SELECT Item FROM @Split WHERE RowIndex=3);
答案 2 :(得分:1)
假设行是有序的,你想要做一个转轴把它们变成列。
另一个选择是让您的解析函数(或修改版本)返回单行结果集(表值函数)并使用CROSS / OUTER APPLY将它们追加到一行: