我想要一种改进我的sql代码的好方法,当条件满足时,我必须使用内部联接。我目前正在复制代码:
@SystemMerge bit if (@SystemMerge=1) BEGIN SELECT ....... FROM myTable INNER JOIN table ON table.param1=myTable.param1 INNER JOIN systemTable on systemTable.param2=myTable.param2 END ELSE BEGIN SELECT ....... FROM myTable INNER JOIN table ON table.param1=myTable.param1 END
我想以这种方式做到这一点:
@SystemMerge bit BEGIN SELECT ....... FROM myTable INNER JOIN table ON table.param1=myTable.param1 ***//the next 4 lines is not working, but this pseudo of what i want:*** if (@SystemMerge=1) begin INNER JOIN systemTable on systemTable.param2=myTable.param2 end
编辑: 解决方案(由于@Damien_The_Unbeliever):
LEFT JOIN systemTable ON systemTable.param2=myTable.param2 WHERE ((@SystemMerge=1 AND systemTable.param2 is not null) OR (@SystemMerge=0 OR @SystemMerge is null))
这应该(大约)执行相同的操作:
SELECT ....... FROM myTable INNER JOIN table ON table.param1=myTable.param1 LEFT JOIN systemTable on systemTable.param2=myTable.param2 and @SystemMerge = 1 WHERE (@SystemMerge = 0 OR systemTable.NonNullableColumn IS NOT NULL)
当然,这还意味着systemTable必须编写对其中的列的任何其他引用,以期望此类列为NULL。
systemTable
NULL