我的postgresql 9.1中有一个带有housenumber的示例表:
drop table if exists mytable;
create table mytable(road_id int, housenr text);
insert into mytable(road_id, housenr) values
('11', '1' ),
('22', '12' ),
('33', '99/1' ),
('44', '88' ),
('55', '2' ),
('66', '28' ),
('77', '29')
;
现在我必须将整个列“housenr”转换为INT字段。 SQL中是否有一种方法只能从可以转换的列中转换这些行。在mytable中,除了“housenr”= 99/1之外,这将是每一行 类似于:FOR EACH ROW IF :: int IS POSSIBLE将行ELSE REMOVE FROM TABLE
答案 0 :(得分:8)
您可以使用REGEX评估列值,以确定它是否为数字:
select * FROM MyTable where (housenr !~ '^[0-9]+$')
这是SQLFiddle:
http://sqlfiddle.com/#!1/d2ff3/9
这是关于〜和〜!
的Postgresql文档http://www.postgresql.org/docs/current/static/functions-matching.html#FUNCTIONS-POSIX-TABLE
答案 1 :(得分:0)
您可以case when
select * from (
select roadid, case when
instr(housenr,"/") > 0 then 0 else cast(housenr as int) end) as housenr_new
from mytable) t
where t.housenr_new <> 0
;
使用regex
时,如果字段不是int
SELECT roadid, CASE WHEN housenr ~ E'^\\d+$'
THEN housenr::integer ELSE 0 END as housenr_new
FROM mytable;