Service Broker - 如何从XML消息中提取行?

时间:2012-07-19 14:50:13

标签: sql-server service-broker

说我有以下情况(用于演示)。简单表格内容转换为XML值,并通过Service Broker发送到另一个SQL服务器,其中SELECT的结果将以非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中提取行的最佳方法是什么,以及如何将它们放到目标表中?

谢谢,彼得

2 个答案:

答案 0 :(得分: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

答案 1 :(得分:1)

和其他选项(我更喜欢Remus 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