我的表中有一个带有 XML 的列,如下所示:
<Notes> <Note>
<Author>test</Author>
<AuthorInitials>JJJ</AuthorInitials>
<Contents>Test treatment notes 3</Contents>
<DateCreated>2013-07-17T14:43:00</DateCreated>
<DateModified>2013-07-17T14:43:00</DateModified>
</Note>
<Note>
<Author>test</Author>
<AuthorInitials>JJJ</AuthorInitials>
<Contents>This is the intial notes test for tasks</Contents>
<DateCreated>2013-07-17T14:36:00</DateCreated>
<DateModified>2013-07-17T14:36:00</DateModified>
</Note>
<Notes> <Note>
<Author>test</Author>
<AuthorInitials>JJJ</AuthorInitials>
<Contents>Test 4 of Task Notes</Contents>
<DateCreated>2013-07-17T14:57:00</DateCreated>
<DateModified>2013-07-17T14:57:00</DateModified>
</Note>
<Note>
<Author>test</Author>
<AuthorInitials>JJJ</AuthorInitials>
<Contents>This is the second note test for tasks</Contents>
<DateCreated>2013-07-17T14:37:00</DateCreated>
<DateModified>2013-07-17T14:37:00</DateModified>
</Note>
我想解析并得到<Contents>
它的一部分。有些字段有多个<Contents>
,所以我需要能够拉出所有字段。
我的想法是使用游标并将结果存储在表中,但我还是 SQL Server 的新手,我认为我并不完全理解它们。
这是我目前拥有的:
DECLARE @temptable TABLE
(
Category varchar(5000),
Notes varchar(5000)
)
DECLARE @Contents varchar(5000)
DECLARE c CURSOR FOR SELECT COMMENTS
FROM EVENT
WHERE COMMENTS <> ''
AND COMMENTS IS NOT NULL
AND ID = 1171438
OPEN c
FETCH NEXT FROM c INTO @Contents
WHILE (@@FETCH_STATUS = 0)
BEGIN
INSERT INTO @temptable (Category, Notes)
SELECT 'Notes',
SUBSTRING(COMMENTS,
(CHARINDEX('<Contents>',
COMMENTS)+10),
(CHARINDEX('</Contents>',
COMMENTS)-CHARINDEX('<Contents>',
COMMENTS)-10))
FROM Event
WHERE COMMENTS <> ''
AND COMMENTS IS NOT NULL
AND ID = 1171438
FETCH NEXT FROM c INTO @Contents
END
CLOSE c
DEALLOCATE c
SELECT *
FROM @temptable
但这仅返回:
Notes | Test treatment notes 3
Notes | Test 4 of Task Notes
Notes | Test treatment notes 3
Notes | Test 4 of Task Notes
知道我错过了什么吗?
编辑:有效的解决方案:
DECLARE @temptable TABLE
(
Category varchar(5000),
Notes XML
)
INSERT INTO @temptable (Category, Notes)
SELECT 'Notes',
COMMENTS
FROM Event
WHERE COMMENTS <> ''
AND COMMENTS IS NOT NULL
AND ID = 1171438
SELECT Category,
Content = XNote.value('(Contents)[1]', 'varchar(5000)')
FROM @temptable
CROSS APPLY Notes.nodes('/Notes/Note') AS Xtbl(Xnote)