在临时表中打开XML插入-SQL 2005 [英] Open XML Insert in Temp table - SQL 2005

查看:107
本文介绍了在临时表中打开XML插入-SQL 2005的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个存储过程,正在传递一个简单的XML:

I have a stored procedure where i am passing a simple XML:

'<Products><ProductId>1</ProductId><ProductId>2</ProductId></Products>'

我在SQL中有一个@temp表,其中有一个ProductId列:

I have a @temp table in SQL which has a ProductId Column:

DECLARE @Temp TABLE (
ProductId NVARCHAR(10)
)     

我需要编写一条插入语句,该语句将循环遍历XML中的ProductId(可以是无限的),并继续插入(在@temp表中),直到XML不再剩余ProductId节点为止.

I need to write an insert statement which will loop through the ProductId's in the XML (which can be infinite) and keep on inserting (in the @temp table) until the XML has no more ProductId nodes left.

涉及游标的解决方案不可行!

A solution involving cursors is not feasible!

以下是我要执行的代码:

Following is the code I am trying to execute:

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".

推荐答案

DECLARE @test XML
    SET @test = '<Products><ProductId>1</ProductId><ProductId>2</ProductId></Products>'

DECLARE @Temp TABLE(ProductId NVARCHAR(10))  

DECLARE @docHandle int 
EXEC sp_xml_preparedocument @docHandle OUTPUT, @doc 

INSERT INTO @Temp(ProductId)
     SELECT t.value('./ProductId[1]','NVARCHAR(10)') AS 'ProductId'
       FROM OPENXML(@docHandle, '//Products', 1) t

EXEC sp_xml_removedocument @docHandle 

这篇关于在临时表中打开XML插入-SQL 2005的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆