用于在字段中迭代XML节点的TSQL语句

时间:2015-02-27 21:24:58

标签: sql-server xml tsql iterator

我有2个字段,其中包含随机值列表,其中列表以空格分隔

field1,field2
2 4 8 4,A B C B

字段中的值和计数是随机的(A并不总是在字段2的索引1中,因此它可以是

field1,field2
2 8,B A

唯一一致的是A B C. 我需要的是总结值并创建列 到目前为止我有这个

SELECT
CAST (N'<H><r>' + REPLACE([field1], ' ', '</r><r>')  + '</r></H>' AS XML) AS [vals],
CAST (N'<H><r>' + REPLACE([field], ' ', '</r><r>')  + '</r></H>' AS XML) AS [cols]
FROM tt

由于某种原因我无法使用像这样的变量

DECLARE @A
    Select 
    CASE WHEN 
    [cols].value('count(/H/r)[1]','VARCHAR(100)') = 'A' THEN @A = @A + [vals].value('count(/H/r)[1]','VARCHAR(100)') END
    from .....

我迷路了我甚至无法为变量分配值并在TSQL中返回数据 我在SELECT语句中尝试了WHILE循环而没有运气

对这个有用的任何帮助

1 个答案:

答案 0 :(得分:0)

也许你不需要while循环?

WITH cte AS (
  SELECT
    --Generate an identifier for each row (if none exists)
    row_id = ROW_NUMBER() OVER(ORDER BY (SELECT 1))
   ,vals   = CAST (N'<val>' + REPLACE([field1], ' ', '</val><val>')  + '</val>' AS XML)
   ,cols   = CAST (N'<col>' + REPLACE([field2], ' ', '</col><col>')  + '</col>' AS XML)
  FROM tt
)
SELECT
  row_id
 ,col_id   = col.value('.','varchar(max)') 
 ,value    = val.value('.','varchar(max)') 
FROM cte
CROSS APPLY vals.nodes('val') v(val)
OUTER APPLY cols.nodes('col') c(col)
WHERE 
  --Get the node position by counting the preceding siblings. Only return rows where val position equals col position.
  val.value('for $i in . return count(../*[. << $i]) + 1', 'int') = col.value('for $i in . return count(../*[. << $i]) + 1', 'int')