逗号分隔值In IN语句(SQL)

时间:2015-10-14 06:07:30

标签: sql sql-server cross-apply

我有一个包含逗号分隔值列的表, 我想将它们作为不同的值并放在另一个select语句的In子句中。我尝试过交叉申请,但没有让它正常工作

表(T1)看起来像:

Empcode Eid Unitcodes
007645  164 UNT111$UNT112$UNT113$
000645  162 UNT100$UNT102$UNT20$UNT97$UNT98$UNT99$UNT136$
002585  163 UNT25$UNT39$
003059  180 UNT76$                                                                                              
000559  165 UNT109$UNT114$UNT166$UNT27$UNT60$UNT103$UNT58$
003049  175 UNT106$UNT54$UNT86$UNT87$UNT130$UNT131$UNT132$
003049  177 UNT51$UNT56$UNT91$UNT92$                                                                            

我需要一个类似的查询:

select * from T2 where empcode='abcd' unitcode in ('UNT111','UNT112','UNT113') 
//only that particular emps Unitcodes from the table T1

3 个答案:

答案 0 :(得分:0)

创建一个函数:此函数将拆分您的值

  Create FUNCTION [dbo].[fn_Split](@text varchar(8000), @delimiter          varchar(20))
   RETURNS @Strings TABLE
  (   
     position int IDENTITY PRIMARY KEY,
     value varchar(8000)  
    )
  AS
  BEGIN

  DECLARE @index int
  SET @index = -1

      WHILE (LEN(@text) > 0)
     BEGIN 
   SET @index = CHARINDEX(@delimiter , @text) 
  IF (@index = 0) AND (LEN(@text) > 0) 
   BEGIN  
INSERT INTO @Strings VALUES (@text)
  BREAK 
END 
  IF (@index > 1) 
 BEGIN  
  INSERT INTO @Strings VALUES (LEFT(@text, @index - 1))  
  SET @text = RIGHT(@text, (LEN(@text) - @index)) 
 END 
ELSE
 SET @text = RIGHT(@text, (LEN(@text) - @index))
END
 RETURN
 END

然后写下你的查询

select * from T2 where empcode='abcd' unitcode in (fn_Split("yourcomma seprated column",',')

答案 1 :(得分:0)

你可以在下面这样做:

<强> QUERY

SELECT * 
FROM #test2
WHERE ID IN (
            SELECT LTRIM(RTRIM(m.n.value('.[1]','varchar(8000)'))) AS Unitcodes
            FROM
                (
                SELECT CAST('<XMLRoot><RowData>' + REPLACE(Unitcodes,'$','</RowData><RowData>') + '</RowData></XMLRoot>' AS XML) AS x
                FROM   #test
                )t
            CROSS APPLY x.nodes('/XMLRoot/RowData')m(n)
            )

示例数据

CREATE TABLE #test
(
   Empcode INT, 
   Eid INT,
   Unitcodes NVARCHAR(MAX)
)
INSERT INTO #test VALUES                                                                                           
(000559,  165, 'UNT109$UNT114$UNT166$UNT27$UNT60$UNT103$UNT58$'),
(003049,  175, 'UNT106$UNT54$UNT86$UNT87$UNT130$UNT131$UNT132$')

CREATE TABLE #test2
(
   ID NVARCHAR(MAX)
)

INSERT INTO #test2 VALUES
('UNT54'),('UNT130'),('UNT999')

<强>输出

ID
UNT54
UNT130

答案 2 :(得分:-1)

试试这个

select * from T2 where empcode='abcd' unitcode in ('%UNT111%','%UNT112%','%UNT113%')