我有一个存储过程,它输出带有列
string_data
的 ResultTable,其行包含类似 - row1: 1,2,3,4 的字符串;第 2 行:2、3、4、5 等。我想使用 string_split
内置函数来分割列的行,并使用交叉应用将每个值作为 int。
我尝试过:
declare @TempTable table (SplitInt int)
exec dbo.ProcName
insert into @TempTable
select *, cast(item as int)
from @TempTable
cross apply string_split(string_data, ',')
您的代码有几个问题。
dbo.ProcName
捕获到 @TempTable
中,但您的语句顺序是错误的(正如 siggemannen 上面指出的那样)。@TempTable
定义 SplitInt int
,但后面的查询需要一个名为 string_data
的字符串。string_split()
函数返回名为value
的列,而不是item
。我已经重写了您的代码来纠正这些问题,这可能会给您一些工作机会。
declare @TempTable table (string_data varchar(max))
insert into @TempTable
exec dbo.ProcName
select *, cast(s.value as int) as SplitInt
from @TempTable t
cross apply string_split(t.string_data, ',') s
结果:
字符串数据 | 价值 | 分割整数 |
---|---|---|
1,2,3,4 | 1 | 1 |
1,2,3,4 | 2 | 2 |
1,2,3,4 | 3 | 3 |
1,2,3,4 | 4 | 4 |
2,3,4,5 | 2 | 2 |
2,3,4,5 | 3 | 3 |
2,3,4,5 | 4 | 4 |
2,3,4,5 | 5 | 5 |
请注意,上面结果中的
value
是字符串,而 SplitInt
是整数。
参见这个数据库<>小提琴。