我有以下查询可获取正确的数据,但它不会以我想要的方式输出。
查询如下:
DECLARE @xml xml = '<review><score>98</score><gameid>99</gameid><reviewdate>11/11/11</reviewdate><reviewtitle>Skyrim : A Real Masterpiece </reviewtitle><reviewdescription>Skyrim is the best open world-game ever made.</reviewdescription></review>';
DECLARE @dataCount int, @currentNodeIndex int;
DECLARE @outputTable TABLE (Rating nvarchar(max), GameId nvarchar(max), DateReviewed nvarchar(max), Title nvarchar(max), Description nvarchar(max));
SET @dataCount = @xml.query('count(/review/*)').value('.', 'int');
SET @currentNodeIndex = 1;
WHILE @currentNodeIndex <= @dataCount
BEGIN
SELECT @xml.query('/node()[1]/node()[sql:variable("@currentNodeIndex")]/node()[1]').value('.', varchar(max)') as Temp
FROM GameData;
SET @currentNodeIndex = @currentNodeIndex + 1;
END
这会生成正确的数据,但是像这样:
Temp
98
Temp
99
Temp
11/11/11
Temp
Skyrim : A Real Masterpiece
Temp
Skyrim is the best open world-game ever made
我希望使用从@outputTable创建的别名在一张表中在一条水平线上显示
就像
Rating GameId DateReviewed Title Description
任何帮助将不胜感激。
答案 0 :(得分:0)
DECLARE @xml xml = '<review><score>98</score><gameid>99</gameid><reviewdate>11/11/11</reviewdate><reviewtitle>Skyrim : A Real Masterpiece </reviewtitle><reviewdescription>Skyrim is the best open world-game ever made.</reviewdescription></review>';
DECLARE @outputTable TABLE (Rating nvarchar(max), GameId nvarchar(max), DateReviewed nvarchar(max), Title nvarchar(max), Description nvarchar(max));
--Do your insert into the temp table with select from xml
INSERT INTO @outputTable
SELECT a.value('score[1]', 'nvarchar(max)') AS [Rating], a.value('gameid[1]', 'nvarchar(max)') AS [GameId], a.value('reviewdate[1]', 'nvarchar(max)') AS [DateReviewed], a.value('reviewtitle[1]', 'nvarchar(max)') AS [Title], a.value('reviewdescription[1]', 'nvarchar(max)') AS [Description]
FROM @xml.nodes('/review') AS x(a)
答案 1 :(得分:0)
要解析xml行并将其输出到查询中,那么我会有所不同。
DECLARE @T TABLE (Data XML)
INSERT INTO @T VALUES
('<review><score>98</score><gameid>99</gameid><reviewdate>11/11/11</reviewdate><reviewtitle>Skyrim : A Real Masterpiece </reviewtitle><reviewdescription>Skyrim is the best open world-game ever made.</reviewdescription></review>'),
('<review><score>100</score><gameid>1002</gameid><reviewdate>11/11/12</reviewdate><reviewtitle>Skyrim : A Real Masterpiece </reviewtitle><reviewdescription>Skyrim is 222the best open world-game ever made.</reviewdescription></review>')
SELECT
Score = Data.value('(/review/score/.)[1]', 'INT'),
GameID = Data.value('(/review/gameid/.)[1]', 'INT'),
ReviewDate = Data.value('(/review/reviewdate/.)[1]', 'NVARCHAR(10)'),
ReviewTitle = Data.value('(/review/reviewtitle/.)[1]', 'NVARCHAR(300)'),
ReviewDescription = Data.value('(/review/reviewdescription/.)[1]', 'NVARCHAR(MAX)')
FROM
@T