日期:2014-05-17  浏览次数:20730 次

sql 查询某个字段为空的时候,更改where 条件 如何实现
select 
case
 when ContractEndTime=''
  then
  (select ContractName from dbo.ContractExecution where ContractBeginTime <'2013-10-1 ')
 else
  (select ContractName from ContractExecution where ContractBeginTime <'2013-10-1 ' and ContractEndTime>'2012-10-1' )
  end 
from dbo.ContractExecution 
--where  
order by ID desc
--消息 512,级别 16,状态 1,第 1 行
-子查询返回的值不止一个。当子查询跟随在 =、!=、<、<=、>、>= 之后,或子查询用作表达式时,这种情况是不允许的。

------解决方案--------------------
SQL code
SELECT  ContractName
 FROM    dbo.ContractExecution
 WHERE   ContractBeginTime < CASE WHEN ContractEndTime = '' THEN '2013-10-1 '
                                  ELSE '2013-10-1 '
                             END
         AND ContractEndTime > CASE WHEN ContractEndTime = '' THEN 0
                                    ELSE '2012-10-1'
                               END
 ORDER BY ID DESC

------解决方案--------------------
1.select ContractName from ContractExecution where ContractBeginTime <'2013-10-1 ' and ContractEndTime>case when ContractEndTime='' then '1900-1-1' else '2012-10-1' end 

2.if ContractEndTime=''
select ContractName from dbo.ContractExecution where ContractBeginTime <'2013-10-1 '
else
select ContractName from ContractExecution where ContractBeginTime <'2013-10-1 ' and ContractEndTime>'2012-10-1' 
以上两种方法都可以实现楼主想要的。