select 语句中的where判断问题
表名:Table1 列名:T1,T2为datetime
id T1 T2
1 2007-12-13 null
2 2007-12-12 null
3 2007-12-15 2007-12-12
4 2007-12-15 null
如果T2不为空,就以T2为查询条件 否则以T1为查询条件
下面是我写的SQL语句,有错误,不知道应该怎摸写
SELECT * FROM Table1
WHERE id= '2 ' AND
(CASE WHEN T1 IS NULL
THEN T1= '2006-12-12 ' ELSE T2= '2006-12-12 ' END)
id=2 和 '2006-12-12 '都是我输入的查询参数
------解决方案--------------------where 语句能带程序吗? 没有用过
------解决方案--------------------SELECT * FROM Table1
WHERE id= '2 ' AND
(T2 IS NULL and T1= '2006-12-12 ' or T2= '2006-12-12 ')
------解决方案--------------------好像不能这么用吧
------解决方案-------------------- ---try
SELECT * FROM Table1
WHERE id= '2 ' AND
T1=CASE WHEN T2 IS NULL
THEN '2006-12-12 ' ELSE T1 END AND T2 = CASE WHEN T2 IS NULL THEN T2 ELSE '2006-12-12 ' END
------解决方案--------------------create table table1(id int, T1 datetime, T2 datetime)
insert table1 select 1, '2007-12-13 ', null
union all select 2, '2007-12-12 ', null
union all select 3, '2007-12-15 ', '2007-12-12 '
union all select 4, '2007-12-15 ', null
select * from table1
where (case when T2 is not null then T2 else T1 end)= '2006-12-12 '
------解决方案--------------------用CASE WHEN 作判斷吧
------解决方案--------------------SELECT * FROM Table1
WHERE id= '2 ' AND convert(varchar(10),isnull(T2,T1),120)= '2006-12-12 '
------解决方案--------------------楼主看看能不能这样做:
SELECT * FROM table1
where
(t2 is not null and t2> '2006-12-12 ') or
(t2 is null and t1 = '2006-12-12 ')