Mysql
 sql >> Database >  >> RDS >> Mysql

Utilizzo delle colonne MySQL TIMESTAMP in SQL Server

A volte è necessario fare un po' di lavoro extra quando si integrano due diversi programmi DBMS. Ecco una soluzione alternativa che abbiamo utilizzato per aiutare un cliente che aveva problemi durante il tentativo di integrazione di SQL Server con MySQL.

Il cliente riceveva il seguente errore in SQL Server quando lavorava con una colonna MySQL TIMESTAMP.

select * from openquery(MYSQL, 'select lastupdated from carriers')
Error converting data type DBTYPE_DBTIMESTAMP to datetime2.

Il motivo alla base di ciò era che nel database MySQL del cliente, i valori DATE, DATETIME o TIMESTAMP non validi venivano automaticamente convertiti in zero (ad esempio '0000-00-00' o '0000-00-00 00:00:00') . Un mese o un giorno zero non è una combinazione di data o ora valida in SQL Server. Per ovviare a questo problema, abbiamo prima convertito la colonna che torna da MySQL in un char(20):

select * from openquery(MYSQL, 'select cast(lastupdated as char(20) ) as
lastupdated from carriers')

Il valore della colonna '0000-00-0000:00:00' è stato quindi convertito in NULL:

select case lastupdated when '0000-00-00 00:00:00' then null else lastupdated
end as lastupdated from openquery(MYSQL, 'select cast(lastupdated as char(20) )
as lastupdated from carriers')

Infine, per riportare la colonna "lastupdated" a un datetime2, abbiamo eseguito:

select cast(x.lastupdated as datetime2) as lastupdated from ( select case
lastupdated when '0000-00-00 00:00:00' then null else lastupdated end as
lastupdated from openquery(MYSQL, 'select cast(lastupdated as char(20) ) as
lastupdated from carriers limit 100') ) x