2

i have a table which have column like this

Actual data    wanted data
0k1/01/1976 --01/01/1976
1-1-1991    --01/01/1991
08/04/1968i -- 08/04/1968
18-05-1987j --  18/05/1987
5d60        -- null
I 5 7 1931  -- Null
12/06/1981v -- 12/06/1981
7-12-2012k  -- 07/12/2012
6r6r6rr7t7t7t -- null

i have tried with PATINDEX and replace functions but unable to move forward

ganesh
  • 95
  • 1
  • 1
  • 3

2 Answers2

3

Create this function

alter function [dbo].[RemoveAlphaCharacters](@Temp nvarchar(1000))
returns nvarchar(1000)
as
begin

    declare @KeepValues as nvarchar(50)
    set @KeepValues = '%[^0-9,/,-]%'
    while patindex(@KeepValues, @Temp) > 0
        set @temp = stuff(@Temp, patindex(@KeepValues, @Temp), 1, '')

    return @temp
end
go

Test

declare @tbl table
(
    DOB nvarchar(20)
)

insert into @tbl 
values('0k1/01/1976'), --01/01/1976
('1-1-1991'),    --01/01/1991
('08/04/1968i'), -- 08/04/1968
('18-05-1987j'), --  18/05/1987
('5d60'),        -- null
('I 5 7 1931'),  -- Null
('12/06/1981v'), -- 12/06/1981
('7-12-2012k'),  -- 07/12/2012
('6r6r6rr7t7t7t') -- null


select  DOB Original, dbo.RemoveAlphaCharacters(DOB) RemoveNumber
        , iif(isdate(dbo.RemoveAlphaCharacters(DOB)) = 1
        , convert(datetime, dbo.RemoveAlphaCharacters(DOB)), null) [DateTime]
from    @tbl

Result

Original        RemoveAlp       DateTime
0k1/01/1976     01/01/1976      1976-01-01 00:00:00.000  
1-1-1991        1-1-1991        1991-01-01 00:00:00.000  
08/04/1968i     08/04/1968      1968-08-04 00:00:00.000  
18-05-1987j     18-05-1987      NULL  
5d60            560             NULL  
I 5 7 1931      571931          NULL  
12/06/1981v     12/06/1981      1981-12-06 00:00:00.000    
7-12-2012k      7-12-2012       2012-07-12 00:00:00.000  
6r6r6rr7t7t7t   666777          NULL  

reference: https://stackoverflow.com/a/1008566/1554116

Community
  • 1
  • 1
Ray Krungkaew
  • 6,652
  • 1
  • 17
  • 28
1

This will work with SQL-server 2005+. The function is only called once instead of 3 times, so this is a bit faster.

SELECT
  DOB Original, 
  RemoveNumber,
  CASE WHEN isdate(RemoveNumber) = 1 
  THEN convert(datetime, RemoveNumber) END [DateTime]
FROM yourtable
CROSS APPLY(SELECT dbo.RemoveAlphaCharacters(DOB) RemoveNumber) x

You will need the function from Rawitas Krungkaew's answer

t-clausen.dk
  • 43,517
  • 12
  • 59
  • 92