像declare @var nvarchar(max) = 'a=2*b=3*c=4|a=10*b=11*c=12|a=20*b=21*c=22'
这样的变量想要将其拆分为表变量
declare @tbl TABLE(a varchar(50),b varchar(50),c varchar(50))
回应必须如下:
a b c
2 3 4
10 11 12
20 21 22
怎么做?
答案 0 :(得分:3)
当您的字段顺序始终排序时,请使用以下命令:
declare @var nvarchar(max) = 'a=2*b=3*c=4|a=10*b=11*c=12|a=20*b=21*c=22'
SET @var = REPLACE(@var, '*', ',')
SET @var = 'SELECT ' + REPLACE(@var, '|', ' UNION ALL SELECT ')
EXEC(@var)
如果您的结果总是有三列,但字段顺序可能会发生变化:
declare @var nvarchar(max) = 'a=2*b=3*c=4|b=10*a=11*c=12|a=20*b=21*c=22'
SET @var = REPLACE(@var, '*', ',')
SET @var = 'SELECT a,b,c FROM (SELECT ' + REPLACE(@var, '|', ') DT UNION ALL SELECT a,b,c FROM (SELECT ') + ') DT'
EXEC(@var)
答案 1 :(得分:0)
由于这是对高级问题的回答,我再添加一个答案:
您可以指定数据类型,并特别转换为德语日期时间和列名称,如下所示:
declare @var nvarchar(max) = 'id=000004650439*dated=22.10.2015*cc=0.27|id=000004650440*dated=30.10.2015*cc=10'
SET @var = REPLACE(@var, '*', ''',')
SET @var = REPLACE(@var, '=', '=''') + ''''
SET @var = 'SELECT CAST(Null As bigint) As Col1, CAST(Null As nvarchar(15)) As Col2, CAST(Null As decimal(10,5)) As Col3 UNION ALL SELECT ' +
REPLACE(@var, '|', ''' UNION ALL SELECT ') + ''
SET @var = 'SELECT Col1, CONVERT(datetime, Col2, 104) As Col2, Col3 FROM (' + @var + ') DT WHERE Col1 IS NOT NULL'
EXEC(@var)