我收到了这个问题:
DECLARE @UserId INT
DECLARE @StateChangeInformation XML
SET @UserId = 1
SET @StateChangeInformation = '<stateChangeInformation EnableOverrideMarking="1"></stateChangeInformation>'
SET @command = 'DECLARE @UserIdXml XML; SET @UserIdXml = ''<userID>{ sql:variable("@UserId") }</userID>''; SET @StateChangeInformation.modify(''insert sql:variable("@UserIdXml") into (/stateChangeInformation)[1]'')'
EXEC sp_executesql @stmt = @command,
@params = N'@StateChangeInformation xml out',
@StateChangeInformation= @StateChangeInformation OUTPUT
SELECT @StateChangeInformation
我想要做的是将XML输出为:
<stateChangeInformation>
<userID>1</userID>
</stateChangeInformation>
目前,我收到以下输出:
<stateChangeInformation EnableOverrideMarking="1">
<userID>"{ sql:variable("@UserId") }"</userID>
</stateChangeInformation>
请帮忙!
答案 0 :(得分:2)
您需要将@UserId
作为参数发送到动态SQL,并使用连接来获取XML中的值。
DECLARE @command nvarchar(max)
DECLARE @UserId INT
DECLARE @StateChangeInformation XML
SET @UserId = 1
SET @StateChangeInformation = '<stateChangeInformation EnableOverrideMarking="1"></stateChangeInformation>'
SET @command = 'DECLARE @UserIdXml XML;
SET @UserIdXml = ''<userID>''+cast(@UserId as varchar(10))+''</userID>'';
SET @StateChangeInformation.modify(''insert sql:variable("@UserIdXml") into (/stateChangeInformation)[1]'')'
EXEC sp_executesql @stmt = @command,
@params = N'@StateChangeInformation xml out, @UserId int',
@StateChangeInformation= @StateChangeInformation OUTPUT, @UserId = @UserId
SELECT @StateChangeInformation