2017-07-27 48 views
0

我想返回Table1中的所有行,以及UserId在該表中具有數據的Table2中的其他列。左連接中使用的可選位參數

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 

預期結果使用參數@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 

使用參數@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

你只需要修復的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; 
+0

完美!謝謝。我會在7分鐘內接受:/ – user3953989