how convert string variable to datetime variable in sql-server?

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?

Answers


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

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

Need Your Help

Routes error for pdf created using prawn

ruby-on-rails pdf ruby-on-rails-4 routes prawn

I have a set of images,I select a single image and pass the src of it to a hidden field using a form

Resetting checkboxes in Android's Alert Dialog

android android-widget

I am using AlertDialog with setMultiChoiceItems to let the user select multiple items which is working fine. The problem is, next time the AlertDialog appears, it still has the items checked. I tried