如何动态解析sql server中的xml数据

问题描述 投票:0回答:1

我试图得到'客户'的节点值,但我需要动态选择这个节点并获取它的值,因为我试图获得主键节点值,我将从其他表中获取该主键现在我有设置变量@primary ='CUSTOMER'但我得到的错误就像

数据类型varchar和xml在add运算符中不兼容。

我尝试使用演员但没有用。任何人都可以帮我这个

    declare @var xml,
@var1 varchar(max),
@var2 varchar(max),
@var3 varchar(max),
@var4 varchar(max),
@var5 varchar(max),
@primary  varchar(max);
set @primary='CUSTOMER';
set @var='<RequestData>
   <CREATED_BY>nachagon</CREATED_BY>
   <CUSTOMER_TYPE />
   <modalid>editmodgrid_iBase_VW_Customers</modalid>
   <Input_Date_From>31-Dec-2007 07:30:00 PM</Input_Date_From>
   <Timestamp>26-Mar-2019 04:02:01 PM</Timestamp>
   <UPDATED_ON />
   <USER_SELECTED_TIMEZONE>Venezuela Standard Time</USER_SELECTED_TIMEZONE>
   <NAME>Kevin Good</NAME>
   <CITY>Stewartsville</CITY>
   <COUNTRY>US</COUNTRY>
   <Input_Date_To>29-Jun-2008 07:30:00 PM</Input_Date_To>
   <UPDATED_BY>nachagon</UPDATED_BY>
   <CREATED_ON>28-Mar-2019 11:57:46 AM</CREATED_ON>
   <CUSTOMER>0000000233</CUSTOMER>
   <oper>edit</oper>
   <id>jqg1</id>
   <tablename>iBase_VW_Customers</tablename>
   <moduleId>Customers</moduleId>
   <LOGGED_IN_USER_ID>11</LOGGED_IN_USER_ID>
</RequestData>'
select  @var1=coalesce(@var1 + ',','')+NodeName , @var2=coalesce(@var2 +',','')+NodeValue 
from (select NodeName,NodeValue from(SELECT  NodeName = C.value('local-name(.)', 'varchar(50)'),
NodeValue = C.value('(.)[1]', 'varchar(50)')  FROM @var.nodes('/RequestData/*') AS T(C))t2  WHERE t2.NodeName NOT IN ('CREATED_BY', 'CREATED_ON', 'id','LOGGED_IN_USER_ID','modalid', 'moduleId','oper','tablename','UPDATED_BY','UPDATED_ON','USER_SELECTED_TIMEZONE'))t
select @var1,@var2 

SET @var5= 'select '+@var+'.value(''(RequestData/'+@primary+')[1]'',''varchar(max)'')'
exec (@var5)
print(@var5)
sql-server xml-parsing
1个回答
0
投票

这个例子可能有帮助

declare @primary nvarchar(max) = 'CUSTOMER';
declare @var xml =
'<RequestData>
   <CREATED_BY>nachagon</CREATED_BY>
   <CUSTOMER_TYPE />
   <modalid>editmodgrid_iBase_VW_Customers</modalid>
   <Input_Date_From>31-Dec-2007 07:30:00 PM</Input_Date_From>
   <Timestamp>26-Mar-2019 04:02:01 PM</Timestamp>
   <UPDATED_ON />
   <USER_SELECTED_TIMEZONE>Venezuela Standard Time</USER_SELECTED_TIMEZONE>
   <NAME>Kevin Good</NAME>
   <CITY>Stewartsville</CITY>
   <COUNTRY>US</COUNTRY>
   <Input_Date_To>29-Jun-2008 07:30:00 PM</Input_Date_To>
   <UPDATED_BY>nachagon</UPDATED_BY>
   <CREATED_ON>28-Mar-2019 11:57:46 AM</CREATED_ON>
   <CUSTOMER>0000000233</CUSTOMER>
   <oper>edit</oper>
   <id>jqg1</id>
   <tablename>iBase_VW_Customers</tablename>
   <moduleId>Customers</moduleId>
   <LOGGED_IN_USER_ID>11</LOGGED_IN_USER_ID>
</RequestData>'


DECLARE @cmd NVARCHAR(MAX) = 'SELECT @xml.value(''(/RequestData/'+@primary+')[1]'', ''nvarchar(max)'' )'
EXECUTE sp_executesql @cmd, N'@xml XML', @xml =  @var

它不是100%防弹,但它可以帮助您实现目标。此外,如果您知道我建议将此类型传递给动态查询的数据类型。

© www.soinside.com 2019 - 2024. All rights reserved.