2015-04-28 43 views
3

我需要在SELECT語句中包含一個XML查詢作爲WHERE謂詞的一部分。使用XML查詢作爲WHERE謂詞的一部分

我有這樣的結構:

DECLARE @tmp TABLE (typeId int, xmlCol xml); 

INSERT INTO @tmp 
    (typeId, xmlCol) 
VALUES 
    (1, '<search><groups><g id="25" /><g id="26" /></groups></search>'), 
    (1, '<search><groups><g id="250" /><g id="9" /></groups></search>'), 
    (2, '<search><groups><g id="25" /><g id="12" /><g id="125" /></groups></search>'); 

SELECT * FROM @tmp; 

但我需要拔出行,其中typeId=1以及其中XML數據包含<g id="25" />。所以在我的例子中,我只能看到結果集中的第一行。

如果可能,我寧願使用XML查詢,而不是將其轉換爲nvarchar並使用LIKE。我試過,但只是得到一個語法錯誤:

SELECT 
    * 
FROM 
    @tmp 
WHERE 
    (typeId = 1) AND 
    (xmlCol.query('/search/groups/g[@id=25])')) 

An expression of non-boolean type specified in a context where a condition is expected, near ')'.

我一直在尋找的例子,但無法找到在以這種方式使用XML查詢。

回答

3

我認爲你必須使用xmlCol.exist而不是查詢。

SELECT 
    * 
FROM 
    @tmp 
WHERE 
    (typeId = 1) AND 
    (xmlCol.exist('/search/groups/g[@id=25]') = 1) 
+0

返回一個錯誤:* XQuery [@ tmp.xmlCol.exist()]:在XQuery表達式結尾處沒有更多的令牌。找到')'。* – EvilDr

+0

刪除了最後一個)現在它是正確的。 – Blim

+0

超級,謝謝。 – EvilDr

2

使用xmlcol.exist。像這樣的東西。

DECLARE @tmp TABLE (typeId int, xmlCol xml); 

INSERT INTO @tmp 
    (typeId, xmlCol) 
VALUES 
    (1, '<search><groups><g id="25" /><g id="26" /></groups></search>'), 
    (1, '<search><groups><g id="250" /><g id="9" /></groups></search>'), 
    (2, '<search><groups><g id="25" /><g id="12" /><g id="125" /></groups></search>'); 

DECLARE @id int = 25 

SELECT * FROM @tmp 
WHERE typeId = 1 
    AND xmlCol.exist('search/groups/g[@id= sql:variable("@id")]') = 1 
+0

可變的例子。非常感謝你。 – EvilDr