0

I have to read dates from a varchar column with the following possible patterns ( month/day/year ):

1/1/2005 
1/13/2005 
10/9/2005 
10/13/2005

What is the correct way to read the day part of those dates with T-SQL?

7
  • Text file? and you want to process it in TSQL? Commented Apr 11, 2014 at 21:27
  • @YuriyGalanter it is irrelevant, anyway i edited the question to avoid confucion. Commented Apr 11, 2014 at 21:30
  • Converting dates stored as text to a database date type has been widely explored. For example, stackoverflow.com/questions/18317650/…. Commented Apr 11, 2014 at 21:31
  • @JonofAllTrades, not the same thing, look to my examples, i have to dig in the string to get only the day. Commented Apr 11, 2014 at 21:34
  • 1
    Yep. So cast it to a date and use DAY(). If you really want to use SUBSTRING() for some reason, please specify. Commented Apr 11, 2014 at 21:36

1 Answer 1

2

Casting to date and using day() would be the correct approach imo:

declare @t table (string varchar(10))
insert @t values ('1/1/2005'),('1/13/2005'),('10/9/2005'),('10/13/2005')
select day(cast(string as date)) as the_day from @t

Would give:

the_day
-----------
1
13
9
13

An alternative if you want to avoid casting would be to use thesubstringandcharindexfunctions:

select 
    substring(
      string, 
      charindex('/', string)+1, 
      charindex('/', string, charindex('/', string)+1)-charindex('/', string)-1
    ) 
from @t
Sign up to request clarification or add additional context in comments.

8 Comments

You can avoid the last cast: select day(string) as the_day from @t
@DavidGriffiths Good point, didn't think that day() operated on anything else than date[time] variables, but thanks to you I now know it can take string literals too. Nice to learn something new :)
I get: The conversion of a nvarchar data type to a datetime data type resulted in an out-of-range value.
@Elio.Batista I'm guessing the date got interpreted as dmy. How the date is interpreted is affected by your language setting. You might have to force it by using set dateformat mdyfirst.
Yes, that is why i wanted to avoid casting to date types, just read the single value from day part.
|

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.