Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 SQL Server 2008 Forums
 Transact-SQL (2008)
 Convert varchar parameter into datetime

Author  Topic 

dachish
Starting Member

12 Posts

Posted - 2012-01-23 : 16:41:43
This is probably something simple but I've never had to convert dates and such before so I'm missing something.

This is for an SSRS report but the actual query is where my issue is.

I have a parameter where users select a date in the format of month-year, ie December-2011.

The problem is the actual date in the database is a normal datetime yyyy-mm-dd format so to get the parameter to actually work, I need to convert it.

I thought it would be something like so:
select @begindate = convert(datetime(mm,@tf1) + '/1/' + convert(datetime(yyyy,@tf1)

Which I thought would put it in a format of mm/1/year but it's not working. I'm sure I have the syntax wrong or something else silly.

Any suggestions?

Thanks!

dachish
Starting Member

12 Posts

Posted - 2012-01-23 : 17:11:08
Nevermind, I may have it.

select @begindate = left(@tf1,charindex('-',@tf1)-1) + ' 1 ' + convert(varchar,right(@tf1,4))
select @enddate = left(@tf1,charindex('-',@tf1)-1) + ' 1 ' + convert(varchar,right(@tf1,4))

Go to Top of Page

Lamprey
Master Smack Fu Yak Hacker

4614 Posts

Posted - 2012-01-23 : 17:34:41
Just for fun, here is a slightly shorter version:
DECLARE @MonthYear VARCHAR(30) = 'December-2011'

SELECT
CONVERT(DATETIME, '01 ' + REPLACE(@MonthYear, '-', ' '), 113),
CONVERT(DATETIME, '01-' + @MonthYear, 113)
Go to Top of Page

jimf
Master Smack Fu Yak Hacker

2875 Posts

Posted - 2012-01-23 : 19:03:04
Even less fun! (or more?)

select dateadd(year,right(@monthyear,4)*1-1900,0)

Jim

Everyday I learn something that somebody else already knew
Go to Top of Page

chriztoph
Posting Yak Master

184 Posts

Posted - 2012-01-23 : 22:06:06
try this one:

SELECT CONVERT(DateTime, REPLACE('December-2011', '-', ''))
Go to Top of Page
   

- Advertisement -