PostgreSQL中::类型转换改CAST语法的正确写法咨询
PostgreSQL标准CAST语法错误排查与正确写法
我正在学习Anthony DeBarros所著的《Practical SQL》一书,在第6章遇到这段使用PostgreSQL特有CAST短格式的代码:
SELECT county_name AS county, state_name AS state, area_water::numeric / (area_land + area_water) * 100 AS pct_water FROM us_counties_pop_est_2019 ORDER BY pct_water DESC;
尝试改用SQL标准CAST语法重写时触发报错,错误代码如下:
SELECT county_name AS county, state_name AS state, area_water CAST (area_water AS numeric) area_water / (area_land + area_water) * 100 AS pct_water FROM us_counties_pop_est_2019 ORDER BY pct_water DESC;
报错信息:
ERROR: syntax error at or near "(" LINE 3: area_water CAST (area_water AS numeric) ^
错误原因
你的代码存在两个问题:
- 多余写了
area_water字段,导致CAST语法前出现无关字段名,直接破坏了SELECT子句的语法结构; - 标准CAST语法要求
CAST(表达式 AS 数据类型)的格式,你在CAST和括号之间加了空格(虽然这不是核心报错原因,但不符合规范写法)。
正确写法
直接用标准CAST函数替换PostgreSQL的::语法即可,不需要额外添加字段名,正确代码如下:
SELECT county_name AS county, state_name AS state, CAST(area_water AS numeric) / (area_land + area_water) * 100 AS pct_water FROM us_counties_pop_est_2019 ORDER BY pct_water DESC;
另外补充:PostgreSQL的area_water::numeric是标准CAST语法的语法糖,两者功能完全等效,只是写法不同。
内容的提问来源于stack exchange,提问作者newbCoder
相关产品推荐
相关产品推荐

