根据参数选择比较运算符

时间:2010-12-19 11:15:55

标签: sql

我想根据参数

比较列

e.g。

  CREATE PROCEDURE [dbo].[usp_GetTenderBySearch]
  (
      p_strOperator char(1),
    p_dtClosingDate datetime
  )
  AS

  Select * From MyTable
  Where Case p_strOperator
        When '=' Then MyColumn = p_dtClosingDate
        When '>' Then MyColumn > p_dtClosingDate
        When '<' Then MyColumn < p_dtClosingDate
  End

有什么建议吗?

2 个答案:

答案 0 :(得分:0)

这个怎么样:

SELECT *
  FROM MyTable
 WHERE (p_strOperator = '=' AND MyColumn = p_dtClosingDate)
    OR (p_strOperator = '>' AND MyColumn > p_dtClosingDate)
    OR (p_strOperator = '<' AND MyColumn < p_dtClosingDate);

答案 1 :(得分:0)

避免非SARGable OR,虽然我不确定这是否更好......

 Where
    Case When p_strOperator = '=' THEN MyColumn ELSE p_dtClosingDate END = p_dtClosingDate
    AND
    Case When p_strOperator = '>' THEN MyColumn ELSE p_dtClosingDate+1 END > p_dtClosingDate
    AND
    Case When p_strOperator = '<' THEN MyColumn ELSE p_dtClosingDate-1 END < p_dtClosingDate