0

データベースに varchar フィールドの不正なデータがあります。データには以下が含まれます:

10/2012
May, 2010
August., 2010
05/10/2009

しかし今、これらのデータをクリーンアップして、列を MM/YYYY 形式で更新する必要があります。これを簡単にするための提案はありますか?

4

3 に答える 3

3

spt_values を使用して月/年変換テーブルを作成し、探している月と年の組み合わせを作成できます。

次に、異なるバージョンに準拠するように月/年の値をフォーマットして結合します。ISDATE(field) <> 1 に対してのみこれを行う必要があることに注意してください

;With ConversionTable as (
SELECT 
    months.number month, 
    years.number year,
    right('00' + cast( months.number as varchar(2)), 2) 
    + '/' + cast(years.number as char(4)) Final
FROM  
     master..spt_values months
    CROSS JOIN master..spt_values years 
WHERE 
     months.NUMBER  between 1 and 12
     and months.type = 'P'
     AND years.NUMBER  between 2000 and 2012
     and years.type = 'P')


SELECT t.baddate , ct.final
FROM 
    TEST t
    INNER JOIN 
    ConversionTable  ct 
    ON t.BadDate = 
         DateName( month , DateAdd( month , ct.month , 0 ) - 1 ) 
         + ', '
         + cast(ct.year as char(4)) 
    OR
      t.BadDate = 
         DateName( month , DateAdd( month , ct.month , 0 ) - 1 ) 
         + '., '
         + cast(ct.year as char(4)) 
    OR 
         t.BadDate = ct.Final

   --- Add more OR statements for your different varieties 
WHERE
     ISDATE(t.badDate) <> 1
UNION
SELECT 
     t.BadDate ,  
        right('00'  + cast(MONTH(Cast(t.BadDate as datetime)) as varchar(2)),2) + '/'
       + cast(year(Cast(t.BadDate as datetime)) as varchar(4))
FROM
     test t
WHERE
     ISDATE(t.badDate) = 1

デモ

于 2012-10-16T19:46:17.560 に答える
2

更新しました

SELECT badDate,
right(convert(varchar(10),cast(replace(CASE len(badDate) - len(replace(badDate, '/', '')) WHEN 1 THEN substring(badDate,1,2)+'/01/'+right(badDate,4) ELSE badDate END,'.', '') AS datetime),103),7)
FROM test

デモ

于 2012-10-16T19:35:33.403 に答える
0

これをコードで行うことをお勧めします (どの言語が利用できるかはわかりません)。ほとんどの言語は、プレーン SQL と比較して、日時処理と例外処理のサポートがはるかに充実しています。

これは、2008 だけでなく SQL Server 2000 および 2005 もサポートする必要がある場合に特に当てはまります。

于 2012-10-16T19:26:39.953 に答える