Quantcast
Channel: Transact-SQL forum
Viewing all articles
Browse latest Browse all 23857

Generate dynamic sql with cte

$
0
0

Hi,

How can generate this SQL from the table @TEMP  ?

select * from a
select * from b where idA = @idA
select * from c where idB = @idB
select * from d where idB = @idB AND idC = @idC AND idB = @idB
select * from e where id = @idD
 
Rules :

When the colunm NeedsParent = NULL that meens I need only id of the n-1 parent
when NeedsParent <> 0 thats meen I need all Ids of parents until I found a parent with NeedsParent = NULL

 

Level  Member   NeedsParent      id
--------------------------------------------
1             a           NULL         id_A
2             b           NULL         id_B
3             c             2             id_C
4             d             3             id_D
5             e           NULL          id_E

 


thx for help

DECLARE @TEMP TABLE([Level] INT,[TABLE] CHAR(1),NeedsParent  int ,Id VARCHAR(10))
INSERT INTO @TEMP VALUES(1,'A' ,NULL, 'id_A')
INSERT INTO @TEMP VALUES(2,'B' ,NULL, 'id_B')
INSERT INTO @TEMP VALUES(3,'C' ,2, 'id_C')
INSERT INTO @TEMP VALUES(4,'D' ,3, 'id_D')
INSERT INTO @TEMP VALUES(5,'E' ,NULL, 'id_E')
SELECT * FROM @TEMP


Viewing all articles
Browse latest Browse all 23857

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>