11
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

PostgreSQLでの暗黙の型変換メモ(文字列<->数値)

Posted at

そういうもんかと諦めていました

以前から不便だなーと思っていたけど

drop table test;
create table test(
  col1 text
);
insert into test values(1);

select * from test where col1 = 1;

#ERROR:  operator does not exist: text = integer
#LINE 7: select * from test where col1 = 1;
                                      ^
#HINT:  No operator matches the given name and #argument type(s). You might need to add explicit type casts.

やれば出来る子

暗黙の型変換を登録してあげると、エラーが出なくなるようです。

-- 数値 <-> 文字列変換
CREATE CAST (int4 AS text) WITH INOUT AS IMPLICIT;
CREATE CAST (text as numeric) WITH INOUT AS IMPLICIT;

-- || 演算子の定義
CREATE FUNCTION textint4cat(text, int4) RETURNS text
   AS 'SELECT $1 || $2::pg_catalog.text' LANGUAGE sql IMMUTABLE STRICT;

CREATE OPERATOR || (PROCEDURE = textint4cat,LEFTARG = text, RIGHTARG = int4);

参考

11
6
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
11
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?