左连接中使用的可选位参数

时间:2017-07-27 02:31:41

标签: sql tsql

我希望返回Table1中的所有行以及Table2中UserId在该表中包含数据的其他列。

Table1
(
    Table1Id int,
    ItemName varchar(50)
)

Table2
(
    Table2Id int,
    Table1Id int,
    UserId int
)

insert into Table1(Table1Id, ItemName)
values (1, 'Item1'), (2, 'Item2'), (3, 'Item3'), (4, 'Item4')

insert into Table2(Table1Id, UserId)
values (1, 1), (2, 1), (4, 1)

create proc testProc 
    @UserId int = null
    @UserOnlyRows bit = 0
as
begin

    select
        *
    from Table1 t1
        left join Table2 t2 on t2.table2Id = t1.table1Id
        and t2.UserId = @UserId
    where (@UserOnlyRows = 1 and t2.UserId is not null)

end

params @UserId = 1,@ UserOnlyRows = 0

的预期结果
Table1Id, ItemName, Table2Id, Table1Id, UserId
----------------------------------------------
1         Item1     1         1         1
2         Item2     2         2         1
3         Item3     NULL      NULL      NULL
4         Item4     3         4         1

params @UserId = 1,@ UserOnlyRows = 1

的预期结果
Table1Id, ItemName, Table2Id, Table1Id, UserId
----------------------------------------------
1         Item1     1         1         1
2         Item2     2         2         1
4         Item3     3         4         1

使用params @UserId = null,@ UserOnlyRows = 0或1

的预期结果
Table1Id, ItemName, Table2Id, Table1Id, UserId
----------------------------------------------
1         Item1     NULL      NULL      NULL
2         Item2     NULL      NULL      NULL
3         Item3     NULL      NULL      NULL
4         Item4     NULL      NULL      NULL

1 个答案:

答案 0 :(得分:1)

您只需修复where子句:

select *
from Table1 t1 left join
     Table2 t2
     on t2.table2Id = t1.table1Id and
        t2.UserId = @UserId
where @UserOnlyRows = 0 or t2.UserId is not null;