Troubled trying to convert a column data type in pgAdmin from varchar to integer (SQL state: 22P02)
Answer a question I am simply trying to convert a column with character varying data type to integer by run this bit of Postgres script: ALTER TABLE tbl.test ALTER COLUMN "XX" TYPE integer USING ("XX"
Answer a question
I am simply trying to convert a column with character varying
data type to integer
by run this bit of Postgres script:
ALTER TABLE tbl.test ALTER COLUMN "XX" TYPE integer USING ("XX"::integer);
and I get this error:
ERROR: invalid input syntax for integer: "XX" SQL state: 22P02
Can someone help me to resolve this issue, please?
Answers
Based on the error you get it looks like you have some values in XX
that cannot be converted to an integer
. You will need to correct those values before issuing the alter table
.
Find your incorrect values with this query:
select "XX" from tbl.test where "XX" !~ '^-{0,1}\d+$';
The !~
is the NOT
regex match. The regex anchors to the beginning of the value with ^
, accounts for an optional minus sign with -{0,1}
, which matches zero or one hyphen character, and then insures that the remaining characters to the end of the value are all digits with \d+$
.
Any values of XX
that fail to match this pattern will be retrieved, and you can figure out how to deal with them either by updating the table or modifying the using
part of your alter table
.
更多推荐
所有评论(0)