Click here to Skip to main content
15,891,033 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi,

I have a stored procedure that return scalar value and I want to implement query like this:
SQL
SELECT @SUM = SUM(table1.id) FROM table1
IF (@param1 IS NOT NULL)
   INNER JOIN table2 ON table1.t2=table2.id
IF (@param2 IS NOT NULL)
   INNER JOIN table3 ON table1.t3=table3.id
WHERE IF (@param1 IS NOT NULL)
          table2.field=@field2
      IF (@param2 IS NOT NULL)
          AND table3.field=@field3

So how could I add these conditions into query?

Thanks in advance.
Posted

Use a Dynamic Sql

SQL
declare @strSql nvarchar(1000) 
declare @param1 nvarchar(10) = ''
declare @param2 nvarchar(10) = ''
set @strSql = 'SELECT @SUM = SUM(table1.id) FROM table1 ' 
IF (@param1 IS NOT NULL)
   set @strSql = @strSql + ' INNER JOIN table2 ON table1.t2=table2.id'
IF (@param2 IS NOT NULL)
   set @strSql = @strSql +' INNER JOIN table3 ON table1.t3=table3.id'
set @strSql = @strSql +' WHERE '
IF (@param1 IS NOT NULL)
          set @strSql = @strSql +' table2.field=@field2'
      IF (@param2 IS NOT NULL)
          set @strSql = @strSql +' AND table3.field=@field3'

print @strSql 
exec sp_executesql @strSql 
 
Share this answer
 
Comments
[no name] 12-Sep-11 8:22am    
good one
Salah_Afa 12-Sep-11 10:47am    
I tried your solution, but this message appeared:
Must declare the scalar variable "@Sum".

But I declare @Sum before the dynamic sql.
????
sachin10d 12-Sep-11 23:49pm    
change the strSql statment as
set @strSql = ' declare @sum int '
set @strSql = @strSql + 'SELECT @SUM = SUM(table1.id) FROM table1 '
Salah_Afa 13-Sep-11 3:23am    
It also didn't work. But I noticed in the debugging mode that the @strSql didn't contain all the text that I set them to it.
So do you have any explanation???
Hi,

the simple solution is that you need to write two sql queries 1 for param1 is not null and another for param2 is not null and combine the result using UNION AL keyword
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900