将int插入xml列sql

时间:2009-07-28 09:53:08

标签: sql-server xml

我如何在xml修改插入语句中插入一个int参数,例如:

DECLARE @holdxml xml
DECLARE @myInt xml

set @myInt = 10

SET @holdxml = (SELECT CAST(VehicleManufacturerXML as xml) FROM VehicleManufacturers WHERE VehicleManufacturerID = 496);

SET @holdxml.modify('insert <VehicleManufacturerID>cast(@myInt, varchar(max))</VehicleManufacturerID> into (/VehicleManufacturers)[1]')

select @holdxml as x
我已经尝试过转换,甚至发现了sql:变量,但似乎什么都没有用? :(

2 个答案:

答案 0 :(得分:2)

在SQL Server 2008中(我相信这是极少数新的XML相关功能之一),您可以编写如下内容:

DECLARE @holdxml xml
DECLARE @myInt xml

set @myInt = '<VehicleManufacturerID>abc</VehicleManufacturerID>'

SET @holdxml = (SELECT CAST(VehicleManufacturerXML as xml) FROM VehicleManufacturers WHERE VehicleManufacturerID = 496);

SET @holdxml.modify('insert sql:variable("@myInt") into (/VehicleManufacturers)[1]')

select @holdxml as x

但我害怕在2005年,这还不行(AFAIK)。在“插入”XML DML语句中使用sql:变量是SQL Server 2008中的新增功能。从SQL Server 2005开始,您可以在其他地方(例如replace value of和其他地方)使用sql:variable。

马克

PS:好的,所以在2005年,我不是百分之百确定这是否可行(不再有2005手头测试它),但你可以试试:

DECLARE @holdxml xml
DECLARE @myInt VARCHAR(MAX)

set @myInt = '<VehicleManufacturerID>abc</VehicleManufacturerID>'

SET @holdxml = (SELECT CAST(VehicleManufacturerXML as xml) FROM VehicleManufacturers WHERE VehicleManufacturerID = 496);

SET @holdxml.modify('insert ' + @myInt + ' into (/VehicleManufacturers)[1]')

select @holdxml as x

只需将@myInt变量设为VARCHAR(MAX),并将.modify语句中的字符串连接在一起。

答案 1 :(得分:0)

我最后使用了替换,这个列实际上是一个带有XML的NTEXT(来自以前站点的旧设计)。我想转换为XML并使用所有可爱的@ XMLPARAM.modify功能然后转换回来,但这些是我最终做的。

--Update Vehicle Options XML

DECLARE @VOXML as nvarchar(MAX)
SET @VOXML = (SELECT VehicleOptions.VehicleOptionXML FROM VehicleOptions WHERE VehicleOptions.VehicleOptionID = @VehOptionID)
SET @VOXML  = replace(@VOXML, '<VehicleOptionID></VehicleOptionID>', '<VehicleOptionID>'+cast(@VehOptionID as nvarchar(MAX))+'</VehicleOptionID>')
SET @VOXML  = replace(@VOXML, '<VehicleModelID title=""Model""></VehicleModelID>', '<VehicleModelID title=""Model"">'+cast(@VehModelID as nvarchar(MAX))+'</VehicleModelID>')

UPDATE VehicleOptions 
SET VehicleOptionXML = @VOXML
WHERE VehicleOptions.VehicleOptionID = @VehOptionID
有趣的是,我的第二个替换似乎没有实现。嗯我调查了一些......

欢呼回应