拆分字符串列值

时间:2015-08-05 02:29:21

标签: sql sql-server sql-server-2008

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 

我想将值 NOT EQUAL 的字符串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.

2 个答案:

答案 0 :(得分:4)

  

子查询返回的值超过1。这是不允许的   子查询跟随=,!=,&lt;,&lt; =,&gt;,&gt; =或当子查询用作   一种表达。声明已经终止。

由于SELECT中的子查询返回多行,因此发生上述错误。尝试执行此操作:

SELECT * FROM SplitStrings('1,2,3',',') x

你会看到它会返回3行,每个项目一行。

要解决此问题,您必须使用CROSS APPLY

SQL Fiddle

SELECT 
    c.acctcode,
    x.primekey AS prime
INTO Chadtblsum
FROM Chadothercharges c
CROSS APPLY SplitStrings(c.groupby,',') x
WHERE groupby <> 'NULL'

答案 1 :(得分:0)

declare  @Table1 TABLE 
    ([acctcode] varchar(4), [primekey] int, [groupby] varchar(8))
;

INSERT INTO @Table1
    ([acctcode], [primekey], [groupby])
VALUES
    ('WDS', 1, NULL),
    ('FDS', 2, NULL),
    ('IRN', 3, NULL),
    ('SUM', 4, '1,2,3'),
    ('STL', 5, NULL),
    ('WTR', 6, NULL),
    ('SUM2', 7, '5,6')
;

select   [acctcode], [primekey],
         Split.a.value('.', 'VARCHAR(100)') AS SubColour  
     FROM  (SELECT [acctcode], [primekey],
             CAST ('<M>' + REPLACE([groupby], ',', '</M><M>') + '</M>' AS XML) AS String  
         FROM  @Table1) AS A CROSS APPLY String.nodes ('/M') AS Split(a)