Wednesday, March 21, 2012

Nested SQL with condition logic

I'm trying to combine two posts I found into one solution but I think I'm going for the impossible.

Here's a shell of the nested select and I've indicated where I'd insert the nested logic.

SELECT node_id, fk_id, nd_src_tbl_name, ( ** conditional code ** )
FROM vNodeCollection as vNc

Here's the nested logic I want to insert for each row:

BEGIN
IF [vNc].nd_src_tbl_name = 'tbl_CorporateRegion'
BEGIN
SELECT cr_textFROM tbl_CorporateRegion WHERE cr_id = [vNc].fk_id
END
ELSE IF [vNc].nd_src_tbl_name = 'tblCountry'
BEGIN
SELECT country_text FROM tbl_Country WHERE country_id = [vNc].fk_id
END
END

I'm trying to be dynamic by storing my table names with my node detail information but I'm starting to realize this may not work well.

Any ideas?No, this will not work. If u want conditional statements in a select, use the CASE functionality. See Books Online for details on how to use it. Alternatively, a user defined function may work as well (if u have SQL Server 2000).|||I forgot about custom functions. After some stumbling with the syntax I was able to make it work. I have no idea if it's efficent though.

Thanks for the idea.

No comments:

Post a Comment