SQL String连接到表

时间:2017-10-11 11:41:40

标签: sql sql-server

给出少量字符串

SET @Codes1 = 3,4
SET @Codes2 = 1
SET @Codes3 = --empty

表 - TblCode

Id   Code
1     A 
2     B
3     C
4     D

如何将带有连接的@Codes1, @Codes2, @Codes3转换为表TblCode,以便返回以下输出:

1. @Codes1 = CD
2. @Codes2 = A
3. @Codes3 = --empty

请注意,输出的串联没有逗号。

PS - 这是一个更大,更复杂的数据集的小例子。请在此处忽略任何错误的设计模式。

2 个答案:

答案 0 :(得分:3)

你可以试试这个。我为@ Codes1添加了答案,但它也适用于@ Codes2和@ Codes3。

DECLARE @TblCode TABLE (Id INT,   Code VARCHAR(2))
INSERT INTO @TblCode
VALUES(1, 'A'), 
(2,'B'),
(3,'C'),
(4,'D')

DECLARE @Codes1 VARCHAR(10) = '3,4'
DECLARE @Codes2 VARCHAR(10) = '1'
DECLARE @Codes3 VARCHAR(10) = NULL

DECLARE @CodesOut VARCHAR(10) = ''


;WITH CTE_1 AS (
    SELECT CODE= @Codes1 + ','
)
, CTE_2 AS -- It silit text to rows
(
    SELECT RIGHT(CTE_1.CODE, LEN(CTE_1.CODE) - CHARINDEX(',',CTE_1.CODE)) CODE , SUBSTRING(CTE_1.CODE, 0, CHARINDEX(',',CTE_1.CODE)) ID, CHARINDEX(',',CTE_1.CODE) AS CI 
    FROM CTE_1 
    UNION ALL
    SELECT RIGHT(CTE_2.CODE, LEN(CTE_2.CODE) - CHARINDEX(',',CTE_2.CODE)) CODE , SUBSTRING(CTE_2.CODE, 0, CHARINDEX(',',CTE_2.CODE)) ID, CHARINDEX(',',CTE_2.CODE) AS CI
    FROM CTE_2  WHERE LEN(CTE_2.CODE) > 0
)
SELECT @CodesOut = @CodesOut + C.Code FROM CTE_2 INNER JOIN @TblCode C ON CTE_2.ID = C.Id

SELECT @CodesOut

结果:

CD

答案 1 :(得分:1)

您可以使用递归CTE。这是一种方法:

with c as (
      select c.*, row_number() over (partition by id) as seqnum
      from c
     ),
     cte as (
      select cast(@codes as varchar(max)) as str,
             replace(@codes, id, code) as newstr,
             1 as lev
      from c
      where seqnum = 1
      union all
      select str, replace(newstr, id, code), lev + 1
      from cte join
           c
           on c.seqnum = cte.lev + 1
     )
select top (1) newstr
from cte
order by lev desc;

如果语法中有错误,请设置SQL Fiddle或Rextester或类似的东西,以便修复它。