2

I'm relatively new to sql-server; I'm trying to have a start-date and end-date pulled from a form-variable as string then convert it into datetime (yyyy-mm-dd) format and I can't seem to find anything that works. Attempted code and resulting error is below. Any advice would be appreciated.

declare @startdate as varchar
declare @enddate as varchar
set @startdate=cast(@startdate as datetime)
set @enddate=cast(@enddate as datetime)

SELECT order_date, inv_no 
from invoices 
where order_date between @startdate and @enddate

The error I keep getting is:

Conversion failed when converting datetime from character string.

How do I fix this?

2
  • You need to specify a length for your variables to begin with to stop them being truncated to 1 character. Also yyyy-mm-dd doesn't work on all locales for datetime. yyyymmdd is more robust. Commented Oct 12, 2012 at 15:09
  • msdn.microsoft.com/en-us/library/ms187928.aspx Commented Oct 12, 2012 at 15:11

2 Answers 2

2

specify a length for your varchar:

declare @startdate as varchar(10)
declare @enddate as varchar(10)
set @startdate=cast(@startdate as datetime)
set @enddate=cast(@enddate as datetime)

SELECT order_date, inv_no 
from invoices 
where order_date between @startdate and @enddate
Sign up to request clarification or add additional context in comments.

Comments

0

you don't have to cast necessarily

declare @startdate varchar(50)
declare @enddate varchar(50)
declare @start datetime = @startdate, @end datetime = @enddate
select @start, @end

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.