SQL无法将变量插入XML列

时间:2014-03-07 18:22:26

标签: sql-server xml sql-server-2012 sqlxml

我有一个数据库,其中包含带有xml列的表日期,该列使用默认的xml数据进行初始化

<data>

</data>

我正在尝试使用变量

插入到该XML列中
DECLARE @UserID INT;
SET @UserID = 10    

DECLARE @DataXML XML;
SET @DataXML = (SELECT TOP 1 d.DataXML 
                FROM [Data] AS d
                WHERE d.UserID = @UserID
                ORDER BY d.LastUpdate DESC );
SELECT @DataXML

DECLARE @Data VARCHAR(MAX) 
SET @Data = '<point>15</point>'

DECLARE @XmlQuery NVARCHAR(max) 
SET @XmlQuery = 'insert ' + @Data + ' as last into (/data)[1]';

DECLARE @sql NVARCHAR(max) 
SET @sql='set @DataXML.modify('''+ @XmlQuery + ''')'

EXEC sp_executesql @sql , N'@DataXML XML OUT', @DataXML OUT

SELECT @DataXML

它更新了具有不更新列的单元格芽的变量

你能帮助我吗?

我正在使用SQL Server 2012

1 个答案:

答案 0 :(得分:0)

-- Setup data...
create table dbo.Data (
  DataID int,
  DataXML xml,
  UserID int,
  LastUpdate datetime
);
insert dbo.Data (DataID, DataXML, UserID, LastUpdate)
values
  (1, N'<data></data>', 10, datetimefromparts(2014, 3, 7, 18, 21, 0, 0)),
  (2, N'<data></data>', 10, datetimefromparts(2014, 3, 7, 18, 22, 0, 0));

-- Find row ID...
declare @UserID int = 10;
declare @DataID int = (
  select top 1 DataID
  from dbo.Data
  where UserID = @UserID
  order by LastUpdate desc
);

-- Update row...
declare @Point int = 15;
update dbo.Data
set DataXML.modify(N' insert <point>{sql:variable("@Point")}</point> into (/data)[1] ')
where DataID = @DataID;

-- Result...
select * from dbo.Data;
<头>
DataID DataXML UserID LastUpdate
1 <数据/> 10 2014-03-07 18:21:00.000
2 15 10 2014-03-07 18:22:00.000