这是我的表
id paydetails
----------- ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
1 <PayDetails><Column Name="NETPAY" DataType="VARCHAR(3000)" Value="40710.00" /><Column Name="EPFAMOUNT" DataType="VARCHAR(3000)" Value="4499.00" /><Column Name="FPFAMOUNT" DataType="VARCHAR(3000)" Value="541.00" /><Column Name="GROSS" DataType="VARCHAR(3000
2 <PayDetails><Column Name="NETPAY" DataType="VARCHAR(3000)" Value="49210.00" /><Column Name="EPFAMOUNT" DataType="VARCHAR(3000)" Value="5549.00" /><Column Name="FPFAMOUNT" DataType="VARCHAR(3000)" Value="541.00" /><Column Name="GROSS" DataType="VARCHAR(3000
所需的输出: -
id NETPAY EPFAMOUNT FPFAMOUNT GROSS PTGROSS
1 40710.00 4499.00 541.00 47200.00 42000.00
2 49210.00 5549.00 541.00 58250.00 50750.00
我尝试过以下代码,但问题是默认情况下它只返回最后一行。因为我传递xml作为参数,我想要每条记录的结果。
declare @xml xml
select @xml = paydetails
from empPayDetails
declare @SQL nvarchar(max) = 'select '+
(
select ',T.X.value(''Column[@Name = "'+T.ColName+'"][1]/@Value'','''+T.DataType+''') as '+quotename(T.ColName)
from (
select T.X.value('@Name', 'nvarchar(128)') as ColName,
T.X.value('@DataType', 'nvarchar(128)') as DataType
from @XML.nodes('/PayDetails/Column') as T(X)) as T
for xml path(''), type
).value('substring(text()[1], 2)', 'nvarchar(max)')+' '+
'from @XML.nodes(''/PayDetails'') as T(X)';
print @sql
exec sp_executesql @SQL, N'@XML xml', @XML;
答案 0 :(得分:0)
查询应为:
declare @SQL nvarchar(max) = 'select '+
(
select ',T.X.value(''Column[@Name = "'+T.ColName+'"][1]/@Value'','''+T.DataType+''') as '+quotename(T.ColName)
from (
select distinct T.X.value('@Name', 'nvarchar(128)') as ColName,
T.X.value('@DataType', 'nvarchar(128)') as DataType
from empPayDetails
cross apply paydetails.nodes('/PayDetails/Column') as T(X)) as T
for xml path(''), type
).value('substring(text()[1], 2)', 'nvarchar(max)')+' '+
'from empPayDetails cross apply paydetails.nodes(''/PayDetails'') as T(X)';
print @sql
exec sp_executesql @SQL;
注意使用cross apply
来使用表的xml列,使用distinct
(否则你将重复相同的列),我删除了参数这一事实exec
。