views:

82

answers:

3

I have a 200 line long stored procedure, which gets a parameter 'prmtr',

What I want to do is add an "sql part" to my stored procedure, according to my parameter.

example:

SELECT A.* FROM
(
SELECT * FROM table1
) A

IF (my parameter) = a

LEFT JOIN
(
SELECT * FROM table2
) B
ON A.ID= B.ID
A: 

Maybe this is useful for you: http://weblogs.sqlteam.com/jeffs/archive/2007/04/03/Conditional-Joins.aspx

Konamiman
+1  A: 

You cannot change a query like this - so you have two choices:

  • have two separate queries in the SPROC (one for each branch) - OK for two, but doesn't scale very well to more complex combinations
  • use dynamic SQL; i.e. build the query in a varchar(4000) and use sp_ExecuteSQL to invoke it; fairly obviously you can change a string to include an extra 'LEFT JOIN ...' etc.

All that said, though, I generally prefer a single SPROC to always return the same schema - it completely messes with most ORM tools if you change the columns based in the parameters. Something to watch...

Marc Gravell
+2  A: 

You can do it like this

SELECT  A.* 
FROM    (
      SELECT * 
      FROM table1
     ) A LEFT JOIN 
     (
      SELECT * 
      FROM table2
     ) B ON @prmt = 'A'
      AND A.ID= B.ID
astander
That works for my question but how about attaching an sql part like "WHERE A.ID IN (SELECT ID FROM newTable)" , depending on my parameter ?
stckvrflw
You could switch a WHERE statement like `WHERE @prmt <> 'A' OR A.ID IN (SELECT ID FROM newTable)`
Andomar
thanks for the cool answers guys. :)
stckvrflw