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.
精彩评论