2015-07-10 258 views
5

我想在PostgreSQL中將smallint轉換爲布爾值。這不箱子的工作,例如:在PostgreSQL中將smallint轉換爲布爾型

select (1::smallint)::bool; 

返回 「錯誤:42846:不能施放SMALLINT類型爲布爾」

我可以在此使用修復:

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

但我想知道是否有方法可以定義如何將smallint直接投射到boolean

原因是我(和我一起工作的其他人)有彙總查詢,這些查詢將數據庫表中的int列轉換爲boolean。我想將此欄更改爲smallint,但這樣做會制約這一邏輯,因爲沒有從smallint直接投射到boolean。是否可以使用postgres CREATE CAST來定義如何將smallint轉換爲boolean

回答

6
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; 
+0

什麼原因PostgreSQL本身不支持這種轉換? – usta