在我下面的查询中,它将所有重新编码集作为 XML 返回到单个变量中。但是我需要将所有父节点值放入单独的 while 循环中。只需运行以下查询:
---------只需声明临时表 ------------------------------------ -------------
IF OBJECT_ID('tempdb.dbo.##TestTable','U')IS NOT NULL DROP TABLE ##TestTable
CREATE TABLE ##TestTable(id int,Uname nvarchar(max),Uaddress nvarchar(max))
INSERT INTO ##TestTable values (1,'abc','NY')
INSERT INTO ##TestTable values (2,'def','WD')
INSERT INTO ##TestTable values (3,'','KL')
DECLARE @XML XML
DECLARE @WhereClause nvarchar(max)
DECLARE @CountVal int
SELECT @CountVal=count(*) from ##TestTable
SET @XML= (SELECT * FROM ##TestTable FOR XML PATH('ParentNode'), ELEMENTS XSINIL)
SELECT @XML
;with cte as
( select xr.value('fn:local-name(.)','nvarchar(max)') name, xr.value('.','nvarchar(max)') val from @xml.nodes('//.') xq(xr)
where xr.value('fn:local-name(.)','nvarchar(max)')<>''
)
SELECT @WhereClause= STUFF((select ' and ' + name + '='''+val+'''' from cte for xml path('')),1,4,'')
SELECT @WhereClause
WHILE (@CountVal>0)
BEGIN
SELECT @WhereClause
SET @CountVal=@CountVal-1
END
IF OBJECT_ID('tempdb.dbo.##TestTable','U')IS NOT NULL DROP TABLE ##TestTable
当前示例 XML(在 @XML 中):
<ParentNode xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"><id>1</id><Uname>abc</Uname><Uaddress>NY</Uaddress></ParentNode><ParentNode xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"><id>2</id><Uname>def</Uname><Uaddress>WD</Uaddress></ParentNode><ParentNode xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"><id>3</id><Uname /><Uaddress>KL</Uaddress></ParentNode>
当前@WhereClause 的输出是(全部在一个@WhereClause 变量中):
ParentNode='1abcNY' and id='1' and Uname='abc' and Uaddress='NY' and ParentNode='2defWD' and id='2' and Uname='def' and Uaddress='WD' and ParentNode='3KL' and id='3' and Uname='' and Uaddress='KL'
但我的预期输出是:
Firstly(in @WhereClause): id='1' and Uname='abc' and Uaddress='NY'
Secondly(in @WhereClause):id='2' and Uname='def' and Uaddress='WD'
Thirdly(in @WhereClause):id='3' and Uname='' and Uaddress='KL'
. .
我怎么得到它。提前致谢。