我试图获取节点值“ customer”,但我需要动态地选择该节点并获取其值,因为我试图获取主键节点值,并且我将从其他表中获取该主键现在我已经设置了变量@primary ='CUSTOMER',但出现类似错误
在add运算符中,数据类型varchar和xml不兼容。
我尝试使用演员表,但没有用。有人可以帮我吗
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)
答案 0 :(得分: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%的防弹措施,但可以帮助您实现目标。 另外,如果您知道数据类型,建议将其也传递给动态查询。