Click here to Skip to main content
15,885,639 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi all,


This is my stored procedure:

SQL
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


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
Posted
Updated 21-Apr-15 3:41am
v2
Comments
Suvendu Shekhar Giri 21-Apr-15 9:45am    
Are you sure your stored procedure name is spTest ? as you are executing spSelectSamplePreScheduleSearch.
ZurdoDev 21-Apr-15 9:47am    
Is SCHEDULE_NEXT_DATE a DateTime column?
Richard Deeming 21-Apr-15 9:51am    
Based on the question, I'd say not:
"SCHEDULE_NEXT_DATE varchar(MAX)"
ZurdoDev 21-Apr-15 9:55am    
Ah, you're right. I didn't see that.

1 solution

Simple - don't store dates in varchar columns. Use one of the many date/time types[^] available to you instead.

Using a varchar column, you need 20 bytes to store a single date. With datetime, you only need 8 bytes; with datetime2, between 6 and 8.

Using a varchar 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 your WHERE clause as well:
SQL
WHERE
    SAMPLE_TYPE = 'SampleSchedule' 
AND 
    Convert(datetime, SCHEDULE_NEXT_DATE, 104) BETWEEN @DateFrom AND @DateTo
 
Share this answer
 
v3
Comments
dannyvkempen 21-Apr-15 9:51am    
I don't have the possibility to change the column type. I already know this makes it a lot easier. That's just the whole problem in this case
Richard Deeming 21-Apr-15 9:55am    
That's annoying. In that case, you'll have to repeat the Convert in the WHERE clause as well. I've updated my answer.
Abhinav S 21-Apr-15 10:02am    
Perfect. 5.
Maciej Los 21-Apr-15 14:19pm    
+5!

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900