这是一个更大的存储过程的一部分,但在我开始之前,我必须先解析XML,提取属性,然后将它们插入到临时表中。然后我将使用该表稍后执行函数。
当我尝试插入临时表时,我得到“Subquery返回的值超过1”。如果我的虚拟XML包含一个节点它工作正常,但如果我添加其他节点问题出现。
完整SQL包括要测试的XML:
DECLARE @MESSAGELIST XML
set @MESSAGELIST =
'<object>
<Record FirstName = ''Red'' LastName = ''Shark'' Email = ''D@d.com'' Date = ''01/01/2001'' ></Record>
<Record FirstName = ''Jon'' LastName = ''Slow'' Email = ''D@d.com'' Date = ''01/01/2011'' ></Record>
<Record FirstName = ''Tyrone'' LastName = ''Lennystar'' Email = ''D@d33.com'' Date = ''01/11/2011'' ></Record>
</object>'
IF (OBJECT_ID('tempdb..#NHOMessagesTemp') IS NOT NULL)
DROP TABLE #NHOMessagesTemp
CREATE TABLE #NHOMessagesTemp
(
FirstName nvarchar(50),
LastName nvarchar(50),
Email nvarchar(100),
MessageDate datetime
)
INSERT INTO #NHOMessagesTemp
VALUES (
(SELECT I.FirstName.value('@FirstName', 'nvarchar(50)')
FROM @MESSAGELIST.nodes('/object/Record') AS I(FirstName)),
(SELECT I.LastName.value('@LastName', 'nvarchar(50)')
FROM @MESSAGELIST.nodes('/object/Record') AS I(LastName)),
(SELECT I.Email.value('@Email', 'nvarchar(100)')
FROM @MESSAGELIST.nodes('/object/Record') AS I(Email)),
(SELECT I.[Date].value('@Date', 'datetime')
FROM @MESSAGELIST.nodes('/object/Record') AS I([Date]))
)
SELECT *
FROM #NHOMessagesTemp
我确定问题出在我的
上FROM @MESSAGELIST.nodes('/object/Record') AS...
但我不知道如何遍历XML并获取所有值。
感谢您的帮助!
答案 0 :(得分:1)
尝试使用此代码从XML获取数据:
SELECT
FirstName = xc.value('@FirstName', 'varchar(50)'),
LastName = xc.value('@LastName', 'varchar(50)'),
Email = xc.value('@Email', 'varchar(50)'),
Date = xc.value('@Date', 'varchar(50)')
FROM
@MESSAGELIST.nodes('/object/Record') AS XT(XC)
并将其插入临时表中,如下所示:
INSERT INTO #NHOMessagesTemp(FirstName, LastName, Email, Date)
SELECT
xc.value('@FirstName', 'varchar(50)'),
xc.value('@LastName', 'varchar(50)'),
xc.value('@Email', 'varchar(50)'),
xc.value('@Date', 'varchar(50)')
FROM
@MESSAGELIST.nodes('/object/Record') AS XT(XC)