如何删除此表中的日期?

时间:2010-08-25 22:47:35

标签: sql sql-server sql-server-2008 date

我有这样的表

create table tbl_1(
  year int,
  month int, 
 day int
)

insert into tbl_1 values(2009,  11, 30)
insert into tbl_1 values(2010,   3,  4)
insert into tbl_1 values(2011,   5, 13)
insert into tbl_1 values(20011, 12, 24)

我想删除2009-11-30至2011-5-13的日期,但我不能,因为所有列都是int,我不能使用此查询:

delete from tbl_1 
 where year >=2009 
   and year<=2011 
   and month >=11 
   and month <=5 
   and day >=30 
   and day <=13

..因为:1&lt;月份&lt; 12和1&lt;一天&lt; 30

我知道这是一个可怕的错误。

我有很多表使用这种方式保存日期,请帮助我,我没有时间删除并重新创建所有这些。

5 个答案:

答案 0 :(得分:7)

你可以这样做:

DELETE FROM tbl_1 
WHERE (year * 10000 + month * 100 + day) BETWEEN 20091130 AND 20110513

我没有测试过这个。我建议先在测试系统上测试它,然后再在生产数据上运行,这样就不会意外删除错误的数据。

答案 1 :(得分:4)

MySQLPostgreSQL

DELETE
FROM    tbl_1
WHERE   (2009, 11, 30) <= (year, month, date)
        AND (year, month, date) <= (2011, 5, 13)

PostgreSQL中你甚至可以这样做:

DELETE
FROM    tbl_1
WHERE   (year, month, date) BETWEEN (2009, 11, 30) AND (2011, 5, 13)

答案 2 :(得分:3)

只需使用更多布尔运算符:

DELETE FROM tbl_1
WHERE (year = 2009 AND (month > 11 OR (month = 11 AND day >= 30)))
OR year = 2010
OR (year = 2011 AND (month < 5 OR (month = 5 AND day <= 13)))

不漂亮,但确实有效。

修改

参数化:

DELETE FROM tbl_1
WHERE (year = %minYear% AND (month > %minMonth% OR (month = %minMonth% AND day >= %minDay%)))
OR (year > %minYear% AND year < %maxYear%)
OR (year = %maxYear% AND (month < %maxMonth% OR (month = %maxMonth% AND day <= %maxDay%)))

答案 3 :(得分:0)

在where子句中将列转换为日期:

DELETE tbl_1
WHERE CONVERT(DATETIME, CONVERT(VARCHAR(4), year) + '-' + convert(VARCHAR(2), month) + '-' + CONVERT(VARCHAR(2), day)) BETWEEN '20091130' AND '20110513'

答案 4 :(得分:0)

最简单的方法是使用DATE_FORMAT。像这样:

...
WHERE DATE_FORMAT( CONCAT(year,"-",month,"-",day), '%Y-%m-%d' ) > "2009-11-30"
AND DATE_FORMAT( CONCAT(year,"-",month,"-",day), '%Y-%m-%d' ) < "2011-05-13"

希望这有帮助! : - )