acctcode primekey groupby <--- columns WDS 1 'NULL' <--- values (varchar) FDS 2 'NULL' IRN 3 'NULL' SUM 4 1,2,3 STL 5 'NULL' WTR 6 'NULL' SUM2 7 5,6
我想分裂字符串groupby列,其中值 不等于 到'NULL' 并保存到另一个表,这将是这样的:
groupby
'NULL'
acctcode primekey groupby SUM 4 1 SUM 4 2 SUM 4 3 SUM2 7 5 SUM2 7 6
这是我的分割字符串代码:
ALTER FUNCTION [dbo].[SplitStrings] ( @List NVARCHAR(MAX), @Delimiter NVARCHAR(255) ) RETURNS TABLE WITH SCHEMABINDING AS RETURN ( SELECT primekey = y.i.value('(./text())[1]', 'nvarchar(4000)') FROM ( SELECT x = CONVERT(XML, '<i>' + REPLACE(@List, @Delimiter, '</i><i>') + '</i>').query('.') ) AS a CROSS APPLY x.nodes('i') AS y(i) );
这是我用来调用该函数的代码:
SELECT acctcode,(SELECT * FROM SplitStrings(groupby,','))as prime INTO Chadtblsum FROM Chadothercharges WHERE acctcode = acctcode
上面的代码给我这个错误:
Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >= or when the subquery is used as an expression. The statement has been terminated.
子查询返回了1个以上的值。当子查询遵循=,!=,<,<=,>,> =或将子查询用作表达式时,不允许这样做。该语句已终止。
由于您的子查询SELECT返回了多行,因此发生了上述错误。尝试执行以下操作:
SELECT
SELECT * FROM SplitStrings('1,2,3',',') x
您会看到它将返回3行,每一项返回一行。
为了解决这个问题,您必须使用CROSS APPLY:
CROSS APPLY
SQL小提琴
SELECT c.acctcode, x.primekey AS prime INTO Chadtblsum FROM Chadothercharges c CROSS APPLY SplitStrings(c.groupby,',') x WHERE groupby <> 'NULL'