postgresql - 在 PostgreSQL 中将 smallint 转换为 boolean

标签 postgresql casting

我正在尝试将 smallint 转换为 PostgreSQL 中的 bool 值。这不是开箱即用的,例如:

select (1::smallint)::bool;

返回“错误:42846:无法将类型 smallint 转换为 bool 值”

我可以使用以下方法解决这个问题:

select (1::smallint)::int::bool;

但我想知道是否有一种方法可以定义如何将 smallint 直接转换为 boolean

这样做的原因是我(以及与我一起工作的其他人)有汇总查询,将数据库表中的 int 列转换为 boolean。我想将此列更改为 smallint,但这样做会破坏此逻辑,因为没有从 smallintboolean 的直接转换。是否可以使用 postgres CREATE CAST 来定义如何将 smallint 转换为 boolean

最佳答案

CREATE OR REPLACE FUNCTION boolean1(i smallint) RETURNS boolean AS $$
    BEGIN
            RETURN (i::smallint)::int::bool;
    END;
$$ LANGUAGE plpgsql;

CREATE CAST (smallint AS boolean) WITH FUNCTION boolean1(smallint) AS ASSIGNMENT;

关于postgresql - 在 PostgreSQL 中将 smallint 转换为 boolean,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31343809/

相关文章:

sql - 如何在 PostgreSQL 中找到 IP 对的最高使用率?

scala - 如何检查对象以查看其类型并返回强制转换的对象

c# - 在 C# 中转换时应该使用 (ObjectType) 还是 'as ObjectType'?

sql - SQL Server 2008 中舍入时的奇怪行为

java - 如何在运行时将字符串转换为整数

postgresql - 使用 docker-compose 在 postgresql 数据库中创建表

postgresql - 为什么我的 Kubernetes 服务运行在不同的子网上?

postgresql - liquibase 中的 Postgres 删除函数显示错误

Postgresql 连接多个表

php - 代码替换