【发布时间】:2009-08-27 18:25:58
【问题描述】:
我有一个存储过程,我在其中传递一个简单的 XML:
'<Products><ProductId>1</ProductId><ProductId>2</ProductId></Products>'
我在 SQL 中有一个 @temp 表,它有一个 ProductId 列:
DECLARE @Temp TABLE (
ProductId NVARCHAR(10)
)
我需要编写一个插入语句,它将遍历 XML 中的 ProductId(可以是无限的)并继续插入(在 @temp 表中),直到 XML 没有更多的 ProductId 节点。
涉及游标的解决方案不可行!
以下是我要执行的代码:
Declare @test XML
SET @test = '<Products><ProductId>1</ProductId><ProductId>2</ProductId></Products>'
DECLARE @Temp TABLE(
ProductId NVARCHAR(10)
)
INSERT INTO @Temp(ProductId)
SELECT tab.col.value('./ProductId[1]','NVARCHAR(10)') AS 'ProductId'
FROM @test
CROSS APPLY
xml_data.nodes('//Products') AS tab(col)
我不断收到错误:
Must declare the table variable "@test".
【问题讨论】:
-
尝试只运行 INSERT 的 SELECT 部分,将 @test 替换为 xml 字符串。确保首先有效
-
不允许我对字符串执行 FROM。
-
是的,需要使用 OPENXML - 请参阅我更新的答案。参考:OPENXML:msdn.microsoft.com/en-us/library/aa276847%28SQL.80%29.aspx
标签: sql sql-server xml insert