0
declare @BranchId int
declare @PaymentDate date

set @DebtIsPayed =null
set @BranchId =3
set @PaymentDate='2013-01-01'

select og.StudentId, og.Name,sb.BranchName,bt.DeptValue,DebtIsPayed,PaymentDate ,bt.DebtDescriptionName
from StudentPayment od 
left outer join DebtDescription bt  on od.DebtDescriptionId= bt.DebtDescriptionId
left outer join Student og on od.StudentId= og.StudentId
left outer join Branch sb on sb.BranchId = og.BranchId
where od.DebtIsPayed=@DebtIsPayed and og.BranchId=@BranchId 

我有一个类似这样的查询,变量来自表单元素(asp.net 应用程序)。我想做的是,如果那些声明的变量为空,列出所有学生付款,如果变量设置为 a 值(例如@DebtIsPayed=1),列出所有学生而不考虑他们的分支。但如果它也设置了 branchId,列出这个分支的所有学生和@DebtIsPayed=1。如果还设置了起息日(@PaymentDate),请列出在此日期之后支付的所有记录,我想我可以用案例来完成,对于所有变化,我可以创建一个查询,但是有没有更好或更简单的方法去做。

4

3 回答 3

1

也许像

where ( 
   (@BranchID is null and od.DebtIsPayed=@DebtIsPayed)
or (@DebtIsPayed is null and og.BranchId=@BranchId)
) and (@PaymentDate is null or PaymentDate > @PaymentDate )
于 2013-07-04T08:56:26.033 回答
1

有一种方法可以在没有 case 运算符的情况下做到这一点。这是示例查询:

declare @BranchId int
declare @PaymentDate date

set @DebtIsPayed =null
set @BranchId =3
set @PaymentDate='2013-01-01'

select og.StudentId, og.Name,sb.BranchName,bt.DeptValue,DebtIsPayed,PaymentDate ,bt.DebtDescriptionName
from StudentPayment od 
left outer join DebtDescription bt  on od.DebtDescriptionId= bt.DebtDescriptionId
left outer join Student og on od.StudentId= og.StudentId
left outer join Branch sb on sb.BranchId = og.BranchId
where (@DebtIsPayed IS NULL OR od.DebtIsPayed=@DebtIsPayed) AND (@BranchId IS NULL OR og.BranchId=@BranchId)

注意 where 语句,如果参数为 null 则不考虑在查询中,如果参数有值,则将其强制执行

于 2013-07-04T08:55:22.373 回答
1

像这样的东西?

select og.StudentId, og.Name,sb.BranchName,bt.DeptValue,DebtIsPayed,PaymentDate ,bt.DebtDescriptionName
from StudentPayment od
left outer join DebtDescription bt  on od.DebtDescriptionId= bt.DebtDescriptionId
left outer join Student og on od.StudentId= og.StudentId
left outer join Branch sb on sb.BranchId = og.BranchId
where (od.DebtIsPayed = @DebtIsPayed or @DebtIsPayed is null) and (og.BranchId = @BranchId or @BranchId is null)

如果缺少参数,它将检索具有任何值的所有学生。

于 2013-07-04T08:55:36.203 回答