SQL用相应的值替换数组字段

时间:2016-06-07 13:19:10

标签: sql sql-server

我有2个SQL表,类似于下面的表:

表-A:

ID | Scenarios
1    1;2;3;4;
2    3;4

table_scenarios:

ID | Unit
1    A
2    B
3    C
4    D

我想要做的是创建一个SQL语句,该语句应该将table_a字段方案中的值替换为table_scenarios中的相应值 输出应如下所示:

ID | Scenarios
1    A;B;C;D;
2    C;D;

如果不使用VBA编码,我怎么能实现这一目标?

2 个答案:

答案 0 :(得分:3)

  

免责声明:正如评论所指出的那样,这远不是构建数据的优化方式。严格来说,你应该重组你的表格,但是如果你这样做是受限制的话,那么下面就可以了。

使用字符串拆分表值函数(从SQL Server Central复制)

CREATE FUNCTION [dbo].[fnSplitString] 
( 
    @string NVARCHAR(MAX), 
    @delimiter CHAR(1) 
) 
RETURNS @output TABLE(splitdata NVARCHAR(MAX) 
) 
BEGIN 
    DECLARE @start INT, @end INT 
    SELECT @start = 1, @end = CHARINDEX(@delimiter, @string) 
    WHILE @start < LEN(@string) + 1 BEGIN 
        IF @end = 0  
            SET @end = LEN(@string) + 1

        INSERT INTO @output (splitdata)  
        VALUES(SUBSTRING(@string, @start, @end - @start)) 
        SET @start = @end + 1 
        SET @end = CHARINDEX(@delimiter, @string, @start)

    END 
    RETURN 
END

使用以下查询后,您可以获得结果:

;
WITH    CTE_Units
          AS (
              SELECT    ta.ID,
                        ts.Unit
              FROM      #table_a AS ta
              CROSS APPLY dbo.fnSplitString(ta.Scenarios, ';') split
              INNER JOIN #table_scenarios AS ts ON split.splitdata = ts.ID
             )
    SELECT  units.ID,
            STUFF((
                   SELECT   ';' + CTE_Units.Unit
                   FROM     CTE_Units
                   WHERE    CTE_Units.ID = units.ID
                  FOR
                   XML PATH('')
                  ), 1, 1, '') + ';' AS Scenarios
    FROM    CTE_Units units
    GROUP BY units.ID;

结果:

Result output

答案 1 :(得分:1)

借助XML和CTE:

DECLARE @xml xml

SELECT @xml = (
SELECT CAST('<i id="'+CAST(ID as nvarchar(max)) + '"><s>' + REPLACE(Scenarios,';','</s><s>') + '</s></i>' as xml)
FROM table_a
FOR XML PATH(''))

;WITH final AS (
SELECT  t.v.value('../@id','int') as Id,
        ts.Unit
FROM @xml.nodes('/i/s') as t(v)
INNER JOIN table_scenarios ts 
    ON ts.ID = t.v.value('.','nvarchar(10)')
)

SELECT DISTINCT id,
        (SELECT Unit +';'
        FROM final f1
        WHERE f.Id = f1.Id
        FOR XML PATH('')
        ) as Scenarios
FROM final f

输出:

id  Scenarios
1   A;B;C;D;
2   C;D;