如何在PostgreSQL中为CTE(公用表表达式)指定列类型?

时间:2012-03-13 00:36:45

标签: postgresql

考虑

WITH t (f0, f1) as (
  values 
     (1, 10),
     (2, 20)     
)...

如何指定f0和f1的类型为bigint?

2 个答案:

答案 0 :(得分:7)

我认为您必须在案例中指定VALUES表达式中的类型:

WITH t (f0, f1) as (
  values 
     (1::bigint, 10::bigint),
     (2, 20)
)...

您只需要第一组值的类型,PostgreSQL可以推断出其余的值。

例如,假设我们有两个函数:

create function f(bigint, bigint) returns bigint as $$
begin
    raise notice 'bigint';
    return $1 * $2;
end;
$$ language plpgsql;

create function f(int, int) returns int as $$
begin
    raise notice 'int';
    return $1 * $2;
end;
$$ language plpgsql;

然后

WITH t (f0, f1) as (
    values
        (1, 10),
        (2, 20)
)
select f(f0, f1) from t;

会给你两个int通知,而

WITH t (f0, f1) as (
    values
        (1::bigint, 10::bigint),
        (2, 20)
)
select f(f0, f1) from t;

会给你两个bigint通知。

答案 1 :(得分:0)

我不知道这是否适合您,但是在DB2中为您推送要指定的列

WITH CTE AS (
SELECT 
    'Apple' AS STRING1
    ,CAST('Orange' AS VARCHAR(10000)) AS STRING2
FROM SYSIBM . SYSDUMMY1)
SELECT * FROM CTE