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.
Author |
Topic |
lmayer4
Starting Member
33 Posts |
Posted - 2012-06-19 : 14:35:22
|
Afternoon,I am migrating data from our old system to our new system and I need to break out the lot field into 2 peices. One being the lot and one being the date. Like so: 42793/EXP.06/1245228/EXP.10/26/13I wrote this:SUBSTRING(lot,1,5) which gives me 42793 and 45228 ...easy now it gets complicated at least for me. How do I take the "date" after the exp. and change it to a datetime? This works great on mm/dd/yy but not for mm/yyCONVERT(datetime, substring(lot,charindex('exp',lot)+4,len(lot))) I get the message :Msg 241, Level 16, State 1, Line 1Conversion failed when converting date and/or time from character string. when I try to convert the mm/yy date. Any thoughts or hints would be great.ThanksLaura |
|
jimf
Master Smack Fu Yak Hacker
2875 Posts |
Posted - 2012-06-19 : 14:51:28
|
You'll need smoething tragic likedeclare @table Table (col1 varchar(30))INSERT INTO @tableVALUES ('42793/EXP.06/12') ,('45228/EXP.10/26/13')select SUBSTRING(Col1,1,5),convert(date,substring(Col1,11,2)+'/01/'+right(col1,2)),LEN(SUBSTRING(Col1,11,20)),CASE WHEN LEN(SUBSTRING(Col1,11,20)) = 5 THEN CONVERT(Date,substring(Col1,11,2)+'/01/'+right(col1,2)) ELSE CONVERT(date,substring(Col1,11,19)) ENDfrom @tablebut this comes with a lot warnings about what formats that field can take. This works on the samples you provided, but caveat emptor!JimEveryday I learn something that somebody else already knew |
 |
|
visakh16
Very Important crosS Applying yaK Herder
52326 Posts |
Posted - 2012-06-19 : 15:15:58
|
[code]SELECT CONVERT(datetime,CASE WHEN LEN(Val) > 5 THEN Val ELSE STUFF(Val,4,0,'01/') END,101) AS DtValFROM(SELECT STUFF(Field,1,PATINDEX('%EXP.%',Field) + 4,'') AS Val FROM table)t[/code]------------------------------------------------------------------------------------------------------SQL Server MVPhttp://visakhm.blogspot.com/ |
 |
|
lmayer4
Starting Member
33 Posts |
Posted - 2012-06-20 : 08:48:10
|
Tragic indeed. Thanks so much for the help Jim! |
 |
|
lmayer4
Starting Member
33 Posts |
Posted - 2012-06-20 : 08:52:06
|
Thanks also Visakh much appreciated. |
 |
|
madhivanan
Premature Yak Congratulator
22864 Posts |
Posted - 2012-06-20 : 08:55:07
|
You need to also set the dateformat optionMadhivananFailing to plan is Planning to fail |
 |
|
|
|
|
|
|