gpt4 book ai didi

sql - 在 select 语句中分配变量

转载 作者:行者123 更新时间:2023-11-29 14:21:10 25 4
gpt4 key购买 nike

我在 postgres 中有一个如下所示的表:

id   score
1 23
2 4
3 42
4 21

在普通 SQL 中,我可以声明一个变量并根据 select 语句的结果为其赋值:

declare @this_score int;
select @this_score = score from scores where id = 3;
print @test_int;

这输出 42。是否可以在 postgres 中以这种方式分配变量?

最佳答案

PostgreSQL 的 SQL 方言没有扩展脚本功能;相反,它希望您使用 PL/PgSQL。在这方面,它更像 Oracle 而不是 Microsoft 的 T-SQL 或 MySQL。

使用 DO block 来运行 PL/PgSQL,或者如果需要返回值,则创建并运行一个函数。

例如

DO
$$
DECLARE
this_score int;
BEGIN
SELECT score FROM scores WHERE id = 3 INTO this_score;
RAISE NOTICE 'this_score is: %', this_score;
END;
$$;

关于sql - 在 select 语句中分配变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26288456/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com