0

There is one column: OpenedDate with datatype: varchar(8) and I want to convert it into datetime but since OpenedDate has erroneous values of 0's. First- I want to convert the 0's into NULLs using the query: CASE WHEN Opened_dt = '0' then 'NULL' else Opened_dt end as 'Opened_dt_converted' Now, I want to use the above results to convert the datatype to DateTime using the syntax: CONVERT(DATETIME, 'Opened_dt_converted',120)

I was thinking if I should use Nested query or create a stored procedure but I am not sure how can I use the nested query for this type of situation? Basically, I want this whole query in one stored procedure. Could you please help me in achieving that task?

Thanks in advance! Geetanjali

4

2 回答 2

3

如果您使用的是 SQL Server 2012+,只需使用try_convert()

select try_convert(DateTime, OpenedDate, 120)

如果它失败了,那么你会得到NULL. 在旧版本中,您只需使用case

select (case when OpenedDate like '[0-9][0-9][0-9]-[0-1][0-9]-[0-3][0-9]'
             then convert(DateTime, OpenedDate, 120)
        end)

注意:我只是输入了一种通常适用于date. time组件类似。

于 2015-03-13T23:42:47.860 回答
1

Sub-select或者CTE应该为你工作。

SELECT CONVERT(DATETIME, Opened_dt_converted, 120) AS dt_converted
FROM   (SELECT CASE
                 WHEN Opened_dt = '0' THEN NULL
                 ELSE Opened_dt
               END AS Opened_dt_converted
        FROM   yourtable) a 

或使用Case语句从转换中跳过零

SELECT CASE
         WHEN Opened_dt = '0' THEN NULL
         ELSE CONVERT(DATETIME, Opened_dt, 120)
       END AS dt_converted
FROM   yourtable 
于 2015-03-13T23:39:35.063 回答