SQL XQuery - 将整数sql变量值插入xml变量

时间:2012-06-06 09:44:29

标签: sql sql-server-2008 xquery-sql

我收到了这个问题:

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>

请帮忙!

1 个答案:

答案 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