我在一张表格里有这样的数据:
year month day ID
2013 1 1 x1
2013 1 2 x2
2013 1 3 x3
2013 1 4 x4
2013 1 5 x5
2013 1 6 x6
...
2016 4 10 x1500此表是一个具有customerID和customerID日期的客户表,但申请日期分为年份& mont & day,数据为2013/1/1至2016/4/10,我希望得到2014/4/5之后申请的customerID。
下面是我尝试过的代码:
SELECT *
FROM table
WHERE [Year]+'-'+[Month]+'-'+[Day] > '2014-4-5'但我得到了这个错误:
当将varchar值'2014-4-5‘转换为数据类型int时,Err 22018 - SQL ServerConversion失败。
有谁能帮帮我呢?
发布于 2016-04-13 09:31:28
Back的解决方案很简单(编辑:但是不正确,谢谢@t-clausen.dk指出这一点),另一种选择是DATEFROMPARTS()。
WHERE DATEFROMPARTS([Year], [Month], [Day]) > '2014-04-05'编辑: DATEFROMPARTS()仅在server 2012及以上版本中可用。
发布于 2016-04-13 09:43:50
这应该可以工作,并保持代码易懂。
SELECT *
FROM table
WHERE
[Year] = 2014 and [Month] = 4 and [Day] > 5
OR [Year] > 2014
OR [Year] = 2014 and [Month] > 4另一个有用的方法是创建一个持久化计算列,持久化列是可以使用的,您甚至可以在该列上添加一个索引:
ALTER TABLE <tablename> ADD actualdate AS
CONVERT(date, cast(year as varchar(4))+'-' +
cast(month as varchar(2)) +'-'+ cast(day as varchar(2)), 126) PERSISTED 然后,您可以简单地键入
WHERE actualdate > '2014-04-05'发布于 2016-04-13 09:38:52
这取决于语言settuings.See这个回答获得更多信息。
create table #test
(
year int,
month int,
date int,
name char(20)
)
insert into #test
select 2012,1,14,'ab'
;with cte
as
(
select *, datefromparts(year,month,date) as datee
from #test
)
select * from cte where date>'somedate'https://stackoverflow.com/questions/36594048
复制相似问题