1

我得到了这个查询:

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>

请帮忙!

4

1 回答 1

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
于 2012-06-06T11:14:38.617 回答