我正在进行可行性研究,以便使用SQL Server 2008在以下结构中存储数据:
-MYTABLE
|ID|RECORDS|BRANCH_OFFICE|MONTH|YEAR
RECORDS列具有XML数据类型,它将如下所示:
<visits>
<visit id="000112233">
<costumer>Mr. One Costumer</costumer>
<date>2011-02-10</date>
<employee>MAT01234</employee>
</visit>
<visit id="000112234">
<costumer>Mr. Another Costumer</costumer>
<date>2011-02-12</date>
<employee>MAT01235</employee>
</visit>
<visit id="000112235">
<costumer>Mr. Some Costumer</costumer>
<date>2011-02-12</date>
<employee>MAT01234</employee>
</visit>
<visit id="000112236">
<costumer>Mr. Some Costumer</costumer>
<date>2011-02-15</date>
<employee>MAT01235</employee>
</visit>
</visits>
我打算用xquery查询xml列,这是存储这些数据的好方法吗?
如果我想获取2011-10中发生的访问列表,添加一个标记,其中包含“日期”标记与现在之间的天数差异,该怎么办?
答案 0 :(得分:2)
针对您的XML的查询可能看起来像这样,我认为您的结构很好。没有必要使用任何花哨的XML东西来获取所需的信息。
declare @T table
(
ID int identity primary key,
Records xml
)
insert into @T values('
<visits>
<visit id="000112233">
<costumer>Mr. One Costumer</costumer>
<date>2011-02-10</date>
<employee>MAT01234</employee>
</visit>
<visit id="000112234">
<costumer>Mr. Another Costumer</costumer>
<date>2011-02-12</date>
<employee>MAT01235</employee>
</visit>
<visit id="000112235">
<costumer>Mr. Some Costumer</costumer>
<date>2011-02-12</date>
<employee>MAT01234</employee>
</visit>
<visit id="000112236">
<costumer>Mr. Some Costumer</costumer>
<date>2011-02-15</date>
<employee>MAT01235</employee>
</visit>
</visits>')
select T.ID,
V.X.value('@id', 'nvarchar(10)') as VisitID,
V.X.value('costumer[1]', 'nvarchar(50)') as Costumer,
V.X.value('date[1]', 'date') as [Date],
V.X.value('employee[1]', 'nvarchar(50)') as Employee
from @T as T
cross apply T.Records.nodes('/visits/visit') as V(X)
结果:
ID VisitID Costumer Date Employee
----------- ---------- -------------------- ---------- --------------------
1 000112233 Mr. One Costumer 2011-02-10 MAT01234
1 000112234 Mr. Another Costumer 2011-02-12 MAT01235
1 000112235 Mr. Some Costumer 2011-02-12 MAT01234
1 000112236 Mr. Some Costumer 2011-02-15 MAT01235