0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【PostgreSQL】空文字をCASTするとinvalid input syntaxエラーになるので対策をする

Last updated at Posted at 2024-06-23

エラー内容

OracleからPostgreSQLへの移行作業中に以下のようなエラーに遭遇しました。PostgreSQLでは空文字とNULLは別モノ扱いなので対策する必要があります。

エラーとなったコード
-- 変数Aには空文字('')が入っている
CAST(変数A AS FLOAT)
エラー文
invalid input syntax for type double precision: ""

「FLOAT型(type double)に対する無効な入力やで」という意味

対策

今回は nullif関数 を使用して対策を行います。nullif関数は第一引数と第二引数が等しい文字列であればnullを返してくれます。

CASTしたい値が変数Aだとします。以下のようにすることで変数Aに空文字が入ればnullが返り、そうでなければ変数Aの文字列がそのまま通ります。

CAST(nullif(変数A,'') AS FLOAT)

参考資料

nullif関数に関しては以下を参照

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?