开发者

How to add a join based on parameter passed in stored procedure

Can I add a inner join or left join or right join based on parameter value. The only way right now I have is writing a dynamic query like

set @sql = 'select * from dbo.products PM(nolock)
'+ case when @orgunit is not null then ' join productorgunit pou on PM.ProductNumber =     pou.开发者_运维问答ProductNumber '
               else ''
          end
         + '
Exec(@sql).

I hope there is something like

Select * from dbo.products PM(nolock)
case when @orgunit is not null then join productorgunit pou on PM.ProductNumber = pou.ProductNumber 

          end  


Can you not just use a LEFT OUTER JOIN?

SELECT PM.*, pou.ProductNumber 
FROM dbo.Products PM LEFT OUTER JOIN ProductOrgUnit pou ON 
                                     PM.ProductNumber = pou.ProductNumber

That will return all records from Products, and only return data from ProductOrgUnit if there is a matching record (otherwise the pou fields will be null in the resultset).

Alternatively you could have two separate queries in your sproc and use a T-SQL IF statement to select which one to run.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜