我與日期,保存在適當的日期格式的其他意見一致是最好的方法,但有時改變數據庫是不可行的。
這裏有一些代碼會將日期從字符串格式轉換爲日期時間,假定月份和年份始終爲2個字符和4個字符,並且日期是唯一的變量長度。
請注意,我將where語句中的日期從'1-05-2015'更改爲'2015-05-01'和'10-06-2015'爲'2015-06-10'。
select date
, cast(right(date, 4)+'-'+SUBSTRING(date, charindex('-', date)+1, 2)+'-'+left(date, charindex('-', date)-1) as datetime) as converted_date
from dates
where
cast(right(date, 4)+'-'+SUBSTRING(date, charindex('-', date)+1, 2)+'-'+left(date, charindex('-', date)-1) as datetime)
>= cast('2015-05-01' as datetime)
and cast(right(date, 4)+'-'+SUBSTRING(date, charindex('-', date)+1, 2)+'-'+left(date, charindex('-', date)-1) as datetime)
<= cast('2015-06-10' as datetime)
來源
2015-06-12 22:16:32
Dan
請回復我 – pankaj
爲什麼您首先將字符存儲爲字符串? – abatishchev