如果满足条件,SQL会执行内连接

时间:2013-07-24 07:48:24

标签: sql sql-server

我想要一个很好的方法来改进我的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))

3 个答案:

答案 0 :(得分:13)

这应该(近似地)做同样的事情:

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

答案 1 :(得分:3)

动态sql怎么样?

declare @sel varchar(max)

set @sel = ' SELECT
         .......
         FROM myTable
         INNER JOIN table ON table.param1=myTable.param1
        '

 if (@SystemMerge=1)  
   begin
     set @sel = @sel+'INNER JOIN systemTable on systemTable.param2=myTable.param2'
   end

exec(@sel)

答案 2 :(得分:1)

如果我是对的简单方法 -

SELECT
    .......
FROM myTable
INNER JOIN table ON table.param1 = myTable.param1
INNER JOIN systemTable on @SystemMerge = 0 or systemTable.param2=myTable.param2