SQL VIEW格式化XML字段类型

时间:2014-10-30 16:42:26

标签: sql sql-server xml

我是一个菜鸟,对我来说这看起来应该很简单,但我已经把我的最后一根头发拉出去试图解决它。

SQL视图返回

  • Announcements
  • 专栏tp_ColumnSet
  • 输入XML

数据:

<datetime1>2014-11-06T08:00:00</datetime1>
<ntext2>&lt;div class="ExternalClass92FCE11907AF41979E054BE04236CCBE"&gt;&lt;p&gt;Open Enrollment Meeting Wednesday, November 5th at 2pm. John Doe will be here to go over our 2014-2015 Medical/Dental &amp;amp; Life Insurance plans and our 401K Plan. We will also have a representative from Joe Medical joining us. Please plan to attend!&lt;/p&gt;&lt;/div&gt;</ntext2>
<nvarchar1>Open Enrollment Meeting</nvarchar1>

我想在视图中显示

字段标题

开放注册会议

Field Body

11月5日星期三下午2点开放注册会议。 John Doe将来到我们的2014-2015医疗/牙科&amp; amp; amp;人寿保险计划和我们的401K计划。我们还将邀请Joe Medical的代表加入我们。请计划参加!

1 个答案:

答案 0 :(得分:0)

您可以通过value()方法从XML字段中提取节点。您基本上向您感兴趣的节点提供XQuery以及应该返回的首选SQL类型。

select tp_ColumnSet.value('(/data/datetime1)[1]', 'datetime') as TheDate
     , tp_ColumnSet.value('(/data/nvarchar1)[1]', 'nvarchar(200)') as TheTitle
     , tp_ColumnSet.value('(/data/ntext2)[1]', 'nvarchar(max)') as TheBody
from Announcements

请注意,我还假设根节点为<data>,因此您可能需要调整代码以适应。

返回:

2014-11-06 08:00:00.000
Open Enrollment Meeting
<div class="ExternalClass92FCE11907AF41979E054BE04236CCBE"><p>Open Enrollment Meeting Wednesday, November 5th at 2pm. John Doe will be here to go over our 2014-2015 Medical/Dental &amp; Life Insurance plans and our 401K Plan. We will also have a representative from Joe Medical joining us. Please plan to attend!</p></div>