如何在存储过程中编写定量列或日期列参数的where子句?

时间:2014-10-20 18:54:21

标签: sql-server stored-procedures

这是一个问题:我需要创建一个get table存储过程,我有很多定量列或日期列,比如

Weight DECIMAL NULL
Cost MONEY NULL
Wattage INT NULL

当我使用

Create PROCEDURE TABLE.P
   @Weight DECIMAL 
   @Cost MONEY 
   @Wattage INT 

   Select 
       Weight, Cost, Wattage 
   From 
       Table
    Where 
       Weight= or @Weight is null
       and Cost=

我不知道如何编写where子句,我知道我应该使用BETWEEN函数但是如何为定量或日期列编写它?

谢谢!

1 个答案:

答案 0 :(得分:1)

如果你使用BETWEEN,你当然需要上下两个值。要获取您在问题中显示的内容并过滤任何传递值的相等性(并忽略任何未传递或传递为NULL的内容),请尝试以下操作:

SELECT Weight, Cost, Wattage
FROM Table
WHERE (@Weight IS NULL OR Weight = @Weight)
  AND (@Cost IS NULL OR Cost = @Cost)
  AND (@Wattage IS NULL OR Wattage = @Wattage)

BETWEEN查询会有更多条件,但 (parameter IS NULL OR condition-using-not-null-parameter) 的一般概念仍然存在。