1

我们有一个将分隔列表转换为表格的函数:

select * from dbo.fn_rpt_ParseValues('abc|123|test','|')

结果:

abc
123
test

如何将每一行放入 SQL 变量中?例如:

@Name = 'abc'
@Phone = '123'
@Comment = 'test'

谢谢!

4

3 回答 3

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
于 2012-05-14T15:34:04.703 回答
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);
于 2012-05-14T14:16:52.180 回答
1

假设这些行是有序的,您想要进行透视以将它们变成列。

另一种选择是让您的解析函数(或修改后的版本)返回单行结果集(表值函数)并使用 CROSS/OUTER APPLY 将它们附加到一行:

http://msdn.microsoft.com/en-us/library/ms174853.aspx

于 2012-05-14T14:20:19.810 回答