1

I am trying to convert my three parameters to a DATETIME but its not working. I get the error that the conversion failed when converting datetime from character string whenever I run this query. Perhaps I am doing in wrong in the conversion? If anyone can provide any feedback.

    @month varchar,
    @day varchar,
    @year varchar

AS
DECLARE @date DATETIME
SET @date = Convert(DateTime, @month + '/' + @day + '/' + @year, 101)

Select *
From events
Where (EDate = @date) OR EDateEnd = @date OR @date Between EDate AND EDateEnd
Order By EDate ASC
2
  • 1
    What are you passing in for each parameter? Commented Apr 21, 2011 at 13:37
  • Your Where expression does confuse me a little bit. Where is the difference between '(EDate = @date)' and 'EDateEnd = (@date)'? Commented Apr 21, 2011 at 13:46

3 Answers 3

3

You need to set the size of your parameters. Probably something like

@month varchar(2),
@day varchar(2),
@year varchar(4)
Sign up to request clarification or add additional context in comments.

Comments

0

That should be working. Make sure you have provided valid values in you parameters.

Update

You should lose the 101 parameter for conversion. Provided that parameters are informed with valid values, this should work for both 2-digit and 4-digit years:

SET @date = Convert(DateTime, @month + '/' + @day + '/' + @year)

Comments

0

This is just a guess, because the conversion function shown should work with the proper parameters.

Are you passing in the year as a two-digit number? If so, try passing it as the full four digit year (which the "101" format expects) OR change it to

SET @date = Convert(DateTime, @month + '/' + @day + '/' + @year, 1) 

if you're passing in a 2 digit year.

(See the difference for with century and without century here: http://msdn.microsoft.com/en-us/library/ms187928.aspx)

EDIT

I have a second guess... The error may not be on the line where you're explicitly converting the parameters into a Datetime variable. This has burned me before... The error MAY be occurring on the following line:

Where (EDate = @date) OR EDateEnd = (@date) OR @date Between EDate AND EDateEnd 

if the EDate column or EDateEnd column is not necessaryly a DateTime column. It could be that THOSE contain the values that can't be converted to a DateTime. (They could be char fields, with a DateTime string stored in them, or they could be actual Date fields with null values stored in them.)

However, without more information about the actual schema of the database it's hard to tell. The best we can do is guess.

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.