SQL where逻辑参数where

SQL Where logic parameterized where

我试图在 SQL 2008 年使用 COALESCE 创建一个参数化的 where 语句,我有一个例子:

Select * 
From Receipts 
Where Receipts.FunctionCode = COALESCE(@FunCode, Receipts.FunctionCode)

希望如果我在@FunCode 中传入 NULL,它将提取所有 7050 条记录。然而,它只撤回了 236 条记录,就好像这是哪里一样: 其中 Receipts.FunctionCode = Receipts.FunctionCode

有人可以解释一下我的逻辑错误吗?对我来说,这个 where 语句应该总是 100% 拉回数据库

这是由于 NULL 值出现在 FunctionCode 列中,试试这个。如果有

,这将使用在 FunctionCode 上创建的索引
Select * 
From Receipts 
Where Receipts.FunctionCode = @FunCode or @FunCode IS NULL