Java

メモ: SQL Server の timestamp 型に insert すると Disallowed implicit conversion from data type datetime to data type timestamp が発生する

・うまくいかなかったこと
MS SQL Server 2008 の timestamp 型のカラムに PreparedStatement#setTimestamp() でデータをセットしようとすると以下の例外が出る。

com.microsoft.sqlserver.jdbc.SQLServerException: Disallowed implicit conversion from data type datetime to data type timestamp, table 'データベース名.dbo.テーブル名', column 'カラム名'. Use the CONVERT function to run this query.

使用した JDBC ドライバは Microsoft SQL Server 2005 JDBC Driver 1.2 (sqljdbc.jar)

・解決方法
カラムのタイプを timestamp 型から datetime 型に変える。

実際には alter table テーブル名 alter column カラム名 新カラムタイプ では変換が出来ないと言われたので
alter table テーブル名 DROP COLUMN カラム名
alter table テーブル名 ADD カラム名 datetime
とし、カラムの削除→追加で回避しました。(テーブルにデータは一件も入っていなかったので)

・参照したサイト
Understanding Data Type Differences

The JDBC TIMESTAMP type maps to the SQL Server datetime and smalldatetime types. The datetime type is stored in two 4-byte integers. The smalldatetime type holds the same information (date and time), but with less accuracy, in two 2-byte small integers.

Note
The SQL Server timestamp type is a fixed-length binary-string type. It does not map to any of the JDBC time types: DATE, TIME, or TIMESTAMP.

ちなみに MySQL では timestamp 型に PreparedStatement#setTimestamp() でセットできました。