如果条件满足,SQL 执行内部联接
问题描述:
我想要一种改进我的 sql 代码的好方法,我必须在满足条件时使用内部联接.我目前正在复制代码:
i want a good way to improve my sql code, i have to use inner join when condition is met. I am currently replicates the code:
@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
我想以这样的方式做到这一点:
and i would like to do it in a way like this:
@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):
edit: the solution (thanks to @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))
答
这应该(大约)做同样的事情:
This should (approxmately) do the same thing:
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
.
Of course, this also means that any other references to columns within systemTable
must be written to expect such columns to be NULL
.