Share via

How to join regular table and xquery resultset

Sudip Bhatt 2,281 Reputation points
2020-09-08T16:44:20.397+00:00

suppose this is my xquery

SELECT d.v.value('(Period/text())[1]','VARCHAR(MAX)') AS Period
FROM @DistinctPeriods.nodes('/Root/NewPeriodData') AS d(v)

Now i want to join period with another table say table1 which has period column.

how to perform this join ?

https://stackoverflow.com/a/8495566/13722367

Developer technologies | Transact-SQL
Developer technologies | Transact-SQL

A Microsoft extension to the ANSI SQL language that includes procedural programming, local variables, and various support functions.


Answer accepted by question author

MelissaMa-msft 24,246 Reputation points Moderator
2020-09-09T04:35:09.983+00:00

Hi @Sudip Bhatt ,

Please have a try with below:

;with cte as (  
SELECT d.v.value('(Period/text())[1]','VARCHAR(MAX)') AS Period  
FROM @DistinctPeriods.nodes('/Root/NewPeriodData') AS d(v))  
  
select * from cte a   
inner join table1  b on a.Period=b.Period  

Best regards
Melissa


If the answer is helpful, please click "Accept Answer" and upvote it.
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

Was this answer helpful?

1 person found this answer helpful.
0 comments No comments

1 additional answer

Sort by: Most helpful
  1. Erland Sommarskog 134.7K Reputation points MVP Volunteer Moderator
    2020-09-08T21:31:55.04+00:00

    Since you are only telling half the story, you leave us guessing. But maybe this is what you are looking for:

    SELECT *  
    FROM   table1  
    WHERE  EXISTS (SELECT *  
                   FROM   @DistinctPeriods.nodes('/Root/NewPeriodData') AS d(v)  
                   WHERE  d.v.value('(Period/text())[1]','int') = table1.period)   
    

    Note that I have changed the data type. I don't what data is in Period, but you would normally not join a varchar(MAX) value.

    Was this answer helpful?

    1 person found this answer helpful.
    0 comments No comments

Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.