陷入sql查询

时间:2011-04-20 09:07:06

标签: sql sql-server-2005

HI

我遇到了像

这样的列的情况
          testColumn
           A;B;C;D;E
           A;B
           C;D

我希望输出为单独的列(我的列数如下例所示,总共有5列)

         A B C D E
         x x x x x
         x x
             X X

3 个答案:

答案 0 :(得分:3)

WITH T(C) AS
(
SELECT 'A;B;C;D;E' UNION ALL
SELECT 'A;B' UNION ALL
SELECT 'C;D'
)
SELECT 
      CASE WHEN CHARINDEX('A',C) > 0 THEN 'X' ELSE '' END AS 'A',
      CASE WHEN CHARINDEX('B',C) > 0 THEN 'X' ELSE '' END AS 'B',
      CASE WHEN CHARINDEX('C',C) > 0 THEN 'X' ELSE '' END AS 'C',
      CASE WHEN CHARINDEX('D',C) > 0 THEN 'X' ELSE '' END AS 'D',
      CASE WHEN CHARINDEX('E',C) > 0 THEN 'X' ELSE '' END AS 'E'
FROM T

给出您想要的结果

A    B    C    D    E
---- ---- ---- ---- ----
X    X    X    X    X
X    X              
          X    X    

答案 1 :(得分:0)

构建存储过程

这可能是一个很好的起点: http://www.codeproject.com/KB/database/SQLArrayParameterHandling.aspx

的问候, //吨

答案 2 :(得分:0)

;with TestTable(testColumn) as
(
  select 'A;B;C;D;E' union all
  select 'A;B' union all
  select 'C;D'
)

select
  case when n.r.exist('r[.="A"]') = 1 then 'X' else '' end as A,
  case when n.r.exist('r[.="B"]') = 1 then 'X' else '' end as B,
  case when n.r.exist('r[.="C"]') = 1 then 'X' else '' end as C,
  case when n.r.exist('r[.="D"]') = 1 then 'X' else '' end as D,
  case when n.r.exist('r[.="E"]') = 1 then 'X' else '' end as E
from TestTable
  cross apply (select cast('<r>'+replace(testColumn, ';', '</r><r>')+'</r>' as xml)) n(r)

结果

A    B    C    D    E
---- ---- ---- ---- ----
X    X    X    X    X
X    X              
          X    X