如何将Dateofbirth列转换为Dateformat(DD / MM / YYYY)

时间:2015-05-06 08:44:35

标签: sql sql-server

我有一个像这样的列的表

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

我尝试过PATINDEX并替换功能但无法继续前进

2 个答案:

答案 0 :(得分:3)

创建此功能

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

测试

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

结果

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  

参考:https://stackoverflow.com/a/1008566/1554116

答案 1 :(得分:1)

这适用于SQL-server 2005+。该函数只调用一次而不是3次,所以速度要快一些。

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

您将需要来自Rawitas Krungkaew的回答

的功能