2012-07-19 61 views
2

假设我有以下情况(用于演示)。简单的表格内容被转换为XML值并通过Service Broker发送到另一个SQL服务器,其中SELECT的结果将以非XML形式(即通常简单的数据库表格)存储。让我们尝试:Service Broker - 如何从XML消息中提取行?

CREATE TABLE tab (a int, b int, c int); 
GO 

INSERT INTO tab (a, b, c) VALUES (1, 11, 111); 
INSERT INTO tab (a, b, c) VALUES (2, 22, 222); 
INSERT INTO tab (a, b, c) VALUES (3, 33, 333); 
INSERT INTO tab (a, b, c) VALUES (4, 44, 444); 
GO 

SELECT * FROM tab FOR XML RAW, TYPE; 
GO 

当捕捉价值的消息,它看起来像:

<row a="1" b="11" c="111" /> 
<row a="2" b="22" c="222" /> 
<row a="3" b="33" c="333" /> 
<row a="4" b="44" c="444" /> 

即单一的多行字符串。我说,我在目标计算机上创建完全相同的表结构:

CREATE TABLE tab_destination (a int, b int, c int); 

什么是从@msg提取行的最佳方式,以及如何将它们投入到目标表?

感谢,切赫

回答

4
CREATE TABLE tab (a int, b int, c int); 
GO 

INSERT INTO tab (a, b, c) VALUES (1, 11, 111); 
INSERT INTO tab (a, b, c) VALUES (2, 22, 222); 
INSERT INTO tab (a, b, c) VALUES (3, 33, 333); 
INSERT INTO tab (a, b, c) VALUES (4, 44, 444); 
GO 

CREATE TABLE tab_destination (a int, b int, c int); 
go 

declare @x xml = (SELECT * FROM tab FOR XML RAW, TYPE); 

insert into tab_destination (a, b, c) 
select 
    x.value('@a', 'int'), 
    x.value('@c', 'int'), 
    x.value('@b', 'int') 
    from @x.nodes('//row') t(x); 
GO 

select * from tab_destination; 
go 

时间阅读xml Data Type Methods

+0

谢谢,它的工作原理。 Remus和@Janis:我正在阅读推荐的文档,但我不明白一个相关的细节。请看看http://stackoverflow.com/questions/11578904/sql-server-how-to-shred-one-multielement-xml-to-single-element-xml-values-ins – pepr 2012-07-20 12:01:08

1

与其他选项(我宁愿莱姆斯Rusanu例子,但..如果大量列和表结构都是一样的,这有助于获得懒惰):

declare @x xml = (SELECT * FROM tab FOR XML RAW, root('tab'), TYPE); 

Declare @docHandle int 
EXEC sp_xml_preparedocument @docHandle OUTPUT, @x 

Select * 
FROM OPENXML(@docHandle, 'tab//', 1) 
With dbo.Tab 

EXEC sp_xml_removedocument @docHandle