简体   繁体   English

SQL Server 2012中“ WHERE”子句中的“ CASE”语句

[英]“CASE” statement within “WHERE” clause in SQL Server 2012

i have a select statement like this 我有一个这样的选择声明

select x, y , z from table a
where CAST( CAST(DATEColumn AS VARCHAR) AS DATE) between  
    case when a.columnx = '1900-01-01' then CAST( CAST(DATEColumn AS VARCHAR) AS DATE) else c.columnx end
    and cast( c.CustomerShipToRecTrmDt as date)

why does this case statement does not work whereas the case statement works if i hardcode the dates? 如果我对日期进行硬编码,为什么此case语句不起作用,而case语句却起作用?

What are you casting a date columns to varchar and then back to a date ? 您将日期列强制转换为varchar然后返回date什么? I think this does what you want: 我认为这可以满足您的需求:

select x, y , z 
rom table a
where DATEColumn  between  
          (case when a.columnx = '1900-01-01' then DATEColumn else cast(c.columnx as date) end and
          cast( c.CustomerShipToRecTrmDt as date)

You can eliminate the case statement from the where clause by doing: 您可以通过执行以下操作从where子句中删除case语句:

where DATEColumn >= cast(c.columnx as date) and DateColumns <= cast( c.CustomerShipToRecTrmDt as date)

The comparison to 1900-01-01 doesn't affect the >= part, unless you are working with dates before 1900 (I'm guessing this is unlikely). 1900-01-01的比较不会影响>=部分,除非您使用的是1900年以前的日期(我想这不太可能)。

Also, whenever casting values to varchar() , always include the length (as in varchar(255) ). 同样,每当将值强制转换为varchar() ,始终包括长度(如varchar(255) )。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM