简体   繁体   English

SQL Server动态XQuery

[英]SQL Server Dynamic XQuery

I'm trying to pull data from XML (stored as NText) in a SQL Table. 我正在尝试从SQL表中的XML(存储为NText)中提取数据。

Suppose we have two tables, each with XML: 假设我们有两个表,每个表都带有XML:

|          TABLE 1          |         |     TABLE 2    |
|ID| NAME  |FIELD_DEFINITION|         |ID|DEF_ID|VALUES|
|1 |FIELD 1|     <XML1>     |         |1 |   1  |<XML2>|
|---------------------------|         |----------------|

And suppose that rows 1 and 2 of XML1 looks like so: 并假设XML1的第1行和第2行看起来像这样:

ROW 1
-----
<def>
    <prop name="Property 1" pdid="1"/>
    <prop name="Property 2" pdid="2"/>
</def>

ROW 2
-----
<def>
    <prop name="Property 1" pdid="3"/>
    <prop name="Property 2" pdid="4"/>
</def>

And XML2 looks like so: XML2看起来像这样:

ROW 1
-----
<ps>
    <p pdid="1" pvalue="Value 1"/>
    <p pdid="2" pvalue="Value 2"/>
</ps>

ROW 2
-----
<ps>
    <p pdid="3" pvalue="Value 3"/>
    <p pdid="4" pvalue="Value 4"/>
</ps>

I'm trying to get all values for any properties named "Property 1" however the definition of the XML that denotes where the value is stored in Table 1 and the values are stored in Table 2. 我正在尝试获取名为“属性1”的任何属性的所有值,但是XML的定义表示该值存储在表1中,而值存储在表2中。

I'm getting the pdid of the Property 1 field for each entry in Table 1 like so: 我得到表1中每个条目的Property 1字段的名称,如下所示:

SELECT
    t1.ID, t1.NAME,
    CAST(t1.FIELD_DEFINITION AS XML).value('(/def/prop[@name = "Property 1"]/@pdid)[1]','varchar(10)') as FIELD_ID
FROM
    [Table 1] t1

But how do I now pass that pdid value into an XQuery to pull the pvalue from Table 2? 但是,现在如何将该pdid值传递到XQuery中以从表2中提取pvalue? I was hoping I could do the above, and join Table 2 to Table 1 on t1.ID = t2.DEF_ID and then pass cp.FIELD_ID into the XQuery on t2.VALUES.value(). 我希望可以完成上述操作,并在t1.ID = t2.DEF_ID表2加入表1,然后将cp.FIELD_ID传递到t2.VALUES.value()上的XQuery中。

Is this possible? 这可能吗? Or am I taking the wrong approach here? 还是我在这里采用错误的方法?

After much head-banging (and "re-allocating" my time away from other work), I've managed to do it, I'll post here for anybody interested. 经过大量的努力(并把我的时间从其他工作中“重新分配”出去)后,我设法做到了,我将在这里张贴给任何感兴趣的人。

SELECT
    t1.ID AS T1_ID, t1.NAME, t2.ID AS T2_ID,
    CAST(CAST(t1.FIELD_DEFINITION AS NVARCHAR(MAX)) + CAST(t2.VALUES AS NVARCHAR(MAX)) AS XML).value
    ('for $d in (/def/prop[@name = "Property 1"]/@pdid)[1] return (/ps/p[@pdid = $d]/@pvalue)[1]','varchar(50)') as VAL
FROM
    [Table 1] t1 INNER JOIN
    [Table 2] t2 ON t1.ID = t2.DEF_ID

Good old FLWOR came to the rescue. 好老的FLWOR来了。 Playing with XML in SQL will never be quick (~6s to return 1000 rows in my case) but it gets the job done! 在SQL中使用XML玩游戏永远不会很快(在我的情况下,大约6秒钟才能返回1000行),但是它可以完成工作!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM