在两个日期之间选择sql server查询
大家好,
这是我的存储过程:
Hi all,
This is my stored procedure:
USE [NCP]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[spTest]
(
@DateFrom datetime,
@DateTo datetime
)
as
begin
set nocount on
SELECT
FORMAT(convert(datetime,SCHEDULE_NEXT_DATE,104), 'yyyy-MM-dd HH:mm:ss') AS SCHEDULE_NEXT_DATE
FROM dbo.TestTable
WHERE
SAMPLE_TYPE = 'SampleSchedule'
AND SCHEDULE_NEXT_DATE BETWEEN @DateFrom AND @DateTo
end
我的TestTable列如下所示:
SCHEDULE_NEXT_DATE varchar(MAX) - 允许空值
当我选择前1000行时数据看起来像这样
SCHEDULE_NEXT_DATE
21-04-2015 10:30
21-04-2015 10:35
22-04-2015 10:30
22-04-2015 10:35
当我用sql profiler检查查询时,我没有得到任何结果。任何人都可以帮我解决这个疑问吗?
exec spTest @ DateFrom ='2015-04-21 10:30:00',@ DateTo ='2015-04- 21 10:35:00'
结果:0行
My TestTable column looks like this:
SCHEDULE_NEXT_DATE varchar(MAX) - Allow Nulls
Data looks like this when i select the top 1000 rows
SCHEDULE_NEXT_DATE
21-04-2015 10:30
21-04-2015 10:35
22-04-2015 10:30
22-04-2015 10:35
When i check the query with sql profiler i get no result. can anyone help me with this query?
exec spTest @DateFrom='2015-04-21 10:30:00',@DateTo='2015-04-21 10:35:00'
Result: 0 rows
简单 - 不要存储日期在varchar
列中。使用众多日期/时间类型之一 [ ^ ]可供您使用。
使用varchar
列,您需要20个字节来存储单个日期。使用datetime
,您只需要8个字节;使用datetime2
,介于6和8之间。
使用varchar
列,没有验证存储的数据。不久,你会找到不同格式的日期;模糊日期(01/02/03应该是1 st 2003年2月,2 nd 2003年1月,或3 rd 2001年2月?);某些随机垃圾,你甚至无法手工转换为日期。
如果无法更改某些列的类型奇怪的是,您还需要转换WHERE
子句中的列:
Simple - don't store dates invarchar
columns. Use one of the many date/time types[^] available to you instead.
Using avarchar
column, you need 20 bytes to store a single date. Withdatetime
, you only need 8 bytes; withdatetime2
, between 6 and 8.
Using avarchar
column, there is no validation of the stored data. Before long, you'll find dates in different formats; ambiguous dates (is "01/02/03" supposed to be 1st Feb 2003, 2nd Jan 2003, or 3rd Feb 2001?); and random junk that you can't even convert to a date by hand.
If you can't change the column type for some bizarre reason, you'll need to convert the column in yourWHERE
clause as well:
WHERE
SAMPLE_TYPE = 'SampleSchedule'
AND
Convert(datetime, SCHEDULE_NEXT_DATE, 104) BETWEEN @DateFrom AND @DateTo