在 PostgreSQL 中声明局部变量?
我正在将应用程序从 MS SQL Server 迁移到 PostgreSQL。在代码中的许多地方我使用局部变量,因此我想进行需要较少工作的更改,所以您能告诉我哪种是翻译以下代码的最佳方法吗?
-- MS SQL Syntax: declare 2 variables, assign value and return the sum of the two
declare @One integer = 1
declare @Two integer = 2
select @One + @Two as SUM
返回:
SUM
-----------
3
(1 row(s) affected)
如果 Postgresql 8.4 甚至 9.0 包含可以简化翻译的重要功能,我将使用它。
There is an almost identical, but not really answered question here.
I am migrating an application from MS SQL Server to PostgreSQL. In many places in code I use local variables so I would like to go for the change that requires less work, so could you please tell me which is the best way to translate the following code?
-- MS SQL Syntax: declare 2 variables, assign value and return the sum of the two
declare @One integer = 1
declare @Two integer = 2
select @One + @Two as SUM
this returns:
SUM
-----------
3
(1 row(s) affected)
I will use Postgresql 8.4 or even 9.0 if it contains significant fetaures that will simplify the translation.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
Postgresql 历史上不支持命令级别的过程代码 - 仅在函数内。但是,在 Postgresql 9 中,添加了对执行内联代码块 有效地支持类似的东西,尽管语法可能有点奇怪,并且与使用 SQL Server 可以做的事情相比有很多限制。值得注意的是,内联代码块无法返回结果集,因此不能用于上面概述的内容。
一般来说,如果您想编写一些过程代码并让它返回结果,您需要将其放在函数中。例如:
据我所知,PostgreSQL 有线协议不允许诸如命令返回多个结果集之类的事情。因此,您不能简单地将 T-SQL 批处理或存储过程映射到 PostgreSQL 函数。
Postgresql historically doesn't support procedural code at the command level - only within functions. However, in Postgresql 9, support has been added to execute an inline code block that effectively supports something like this, although the syntax is perhaps a bit odd, and there are many restrictions compared to what you can do with SQL Server. Notably, the inline code block can't return a result set, so can't be used for what you outline above.
In general, if you want to write some procedural code and have it return a result, you need to put it inside a function. For example:
The PostgreSQL wire protocol doesn't, as far as I know, allow for things like a command returning multiple result sets. So you can't simply map T-SQL batches or stored procedures to PostgreSQL functions.
您可以在
DECLARE
子句中使用:=
、=
声明局部变量,如下所示:*Memos:
:=
、=
和DEFAULT
是相同的。value4
会出错。value5
为NULL
。DO
语句中使用DECLARE
子句声明局部变量。然后,调用
my_func()
返回6
,如下所示:You can declare local variables with
:=
,=
inDECLARE
clause as shown below:*Memos:
:=
,=
andDEFAULT
are the same.value4
gets error.value5
isNULL
.DECLARE
clause in a PL/pgSQL function and procedure andDO
statement.Then, calling
my_func()
returns6
as shown below: