Search code examples
sqlsql-serverxmlsqlxml

Write subquery in xml.exist()


I have a table with one column:

IF OBJECT_ID('tempdb..#tmp') IS NOT NULL DROP TABLE #tmp
CREATE TABLE #tmp
(
data XML
)GO

with one record:

INSERT INTO #tmp
VALUES ( N'<RelevanExpertXML><Tel><RelevanExpert>1</RelevanExpert></Tel><Tel><RelevanExpert>2</RelevanExpert></Tel></RelevanExpertXML>')

and another tale with one column

CREATE TABLE #tmp2
(
id int
)
GO

and i want to write this query:

select * 
from #temp
where xml.exist('/RelevanExpertXML/Tel/RelevanExpert[(text()) = [select id from     #temp2]]') = 1

in fact i want to write sub query in exist(), but i get error, and also i can't change from clause and select list, only i can change where clause.

thanks for help.


Solution

  • you can use this query:

    select * 
    from #tmp
    where exists
        (
           select * 
           from #tmp2 as t
           where
               #tmp.data.exist('/RelevanExpertXML/Tel/RelevanExpert[(text()) = sql:column("t.id")]') = 1
        )
    

    but it will return you the whole xml. If you want to split xml by rows, you have to use nodes() function in the from clause.