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
 SQL Server 2008 Forums
 Transact-SQL (2008)
 case statement which includes inner join...

Author  Topic 

doubleotwo
Yak Posting Veteran

69 Posts

Posted - 2010-06-25 : 15:03:38
is it possible to add an inner join to the sql statement
with an case ?

really curious about this

if a specific @var is filled , it should add the inner join, if not , do nothing.. :)

webfred
Master Smack Fu Yak Hacker

8781 Posts

Posted - 2010-06-25 : 15:20:47
No.
That is only possible using dynamic sql.


No, you're never too old to Yak'n'Roll if you're too young to die.
Go to Top of Page

doubleotwo
Yak Posting Veteran

69 Posts

Posted - 2010-06-25 : 15:40:41
no offence i dont want to be a fucker but it is... just found it... but it doesnt seem to does the job
think there is an error in the other part of the statement

you can do it by just duplicate the exact query and setting an if statement at top...
in IF u add the inner join, in the ELSE you dont...

you say dynamic sql, is this building the sql statemnent into a variable ? or is this something else ?
Go to Top of Page

webfred
Master Smack Fu Yak Hacker

8781 Posts

Posted - 2010-06-26 : 06:33:54
To have 2 statements - one in IF and the other in ELSE isn't what you have asked for.
So my answer was that it isn't possible.

Yes, dynamic sql means to build the statement into a variable and then execute it.


No, you're never too old to Yak'n'Roll if you're too young to die.
Go to Top of Page

Sachin.Nand

2937 Posts

Posted - 2010-06-27 : 09:28:48
quote:
Originally posted by doubleotwo

is it possible to add an inner join to the sql statement
with an case ?

really curious about this

if a specific @var is filled , it should add the inner join, if not , do nothing.. :)





Yes it is possible without need for dynamic SQL.Have a look below



declare @tbl as table(id int)
insert into @tbl
select 1 union all
select 1

declare @var int=1

select * from @tbl t1
inner join @tbl t2 on t1.id=case when @var=1 then t2.id else 0 end





Limitations live only in our minds. But if we use our imaginations, our possibilities become limitless.

PBUH
Go to Top of Page
   

- Advertisement -