Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 General SQL Server Forums
 New to SQL Server Programming
 JOIN table if required

Author  Topic 

tech_1
Posting Yak Master

129 Posts

Posted - 2014-09-23 : 16:15:09
in SQL Server 2008+, is there a way to join a table if there is need to?
for example, without using Dynamic SQL to construct a sql string, I want to be able to select fields from a main table.
But then, I may have a parameter to do a search on a column but that column is in another table which requires a join.

would a LEFT OUTER JOIN be sufficient where if the parameter is not supplied then it doesn't matter and ignores to do a match but if it is supplied then I can do a match (and using a CASE statement to determine if there is a need to do a match if the param is not null)

gbritton
Master Smack Fu Yak Hacker

2780 Posts

Posted - 2014-09-23 : 16:34:46
YOu can join with a predicate of a = b OR NOT <expression that returns true if parameter is supplied>
Go to Top of Page

madhivanan
Premature Yak Congratulator

22864 Posts

Posted - 2014-09-29 : 05:30:22
Why don't you just use IF Statement?

If @param is null
SQL statement without extra table
else
SQL statement with extra table and apply filter



Madhivanan

Failing to plan is Planning to fail
Go to Top of Page

tech_1
Posting Yak Master

129 Posts

Posted - 2014-09-29 : 05:54:17
the SQL statement is already large... I don't want to have to maintain 2 parts of the big statements :)
Go to Top of Page

gbritton
Master Smack Fu Yak Hacker

2780 Posts

Posted - 2014-09-29 : 09:36:36
How large? Please post your entire query and indicate where you want the conditional join.
Go to Top of Page
   

- Advertisement -