首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 数据库 > SQL Server >

有没有可能把Case when 话语当作where的条件表达式

2012-07-29 
有没有可能把Case when 语句当作where的条件表达式?如表Field1Field2A2012-1-1B2012-2-1C2012-3-1D

有没有可能把Case when 语句当作where的条件表达式?
如表
  Field1 Field2
  A '2012-1-1'
  B '2012-2-1'
  C '2012-3-1'
  D '2012-4-1'
想要的结果是
select * from [table] where case when Field='a' then Field2>'2012-2-1' when Field1='c' then Fied3 between '2012-1-1' and '2012-5-1' else Field2>'2012-1-1' end
返回  
  B '2012-2-1'
  C '2012-3-1'
  D '2012-4-1'

或者有变通的办法也行

[解决办法]

SQL code
where (Field='a' and Field2>'2012-2-1')or(Field1='c' and Fied3 between '2012-1-1' and '2012-5-1')or(Field2>'2012-1-1')
[解决办法]
SQL code
IF EXISTS (SELECT 1 FROM SYSOBJECTS WHERE name = 'tba')BEGIN    DROP TABLE tbaENDGOCREATE TABLE tba(    Field1 VARCHAR(10),    Field2 VARCHAR(10))GOINSERT INTO tbaSELECT 'A', '2012-01-01' UNIONSELECT   'B', '2012-02-01' UNIONSELECT   'C', '2012-03-01' UNIONSELECT   'D', '2012-04-01'GO                        select * from tba where Field2 BETWEEN CASE when Field1 ='A' then '2012-02-01'                      else '2012-01-01' end  AND CASE WHEN Field1 = 'C' THEN '2012-05-01'                                                   ELSE Field2 END/*Field1    Field2B    2012-02-01C    2012-03-01D    2012-04-01*/
[解决办法]
SQL code
select * from [table] where Field='a' and Field2>'2012-2-1'union allselect * from [table] where Field1='c' and Fied3 between '2012-1-1' and '2012-5-1'union allselect * from [table] where Field2>'2012-1-1'
[解决办法]
SQL code
case when  可以用在 SELECT 、WHERE  、ORDER BY  后面
[解决办法]
探讨
2和4楼的代码是能解决问题,我想提高的是速度和较少的代码,如果有10个字段,每种字段又有2种情况,那用or连接效率太低,用union可是要写2^10的sql语句了

[解决办法]
SQL code
select * from [table] where Field='a' and Field2>'2012-2-1'union allselect * from [table] where Field1='c' and Fied3 between '2012-1-1' and '2012-5-1'union allselect * from [table] where Field2>'2012-1-1' and Field!='a' and Field!='c'
[解决办法]
探讨

2和4楼的代码是能解决问题,我想提高的是速度和较少的代码,如果有10个字段,每种字段又有2种情况,那用or连接效率太低,用union可是要写2^10的sql语句了

[解决办法]
http://blog.csdn.net/dba_huangzj/article/details/7684520看看我翻译的,说不定有帮助

热点排行