使用 MSSQL 很容易,@ 标记所有变量名称的开头,让解析器知道它是一个变量而不是列。
这对于注入常量值之类的事情很有用,其中选择在从临时表复制时向插入表提供输入。
declare @foo varchar(50) = 'bar';
select @foo;
Run Code Online (Sandbox Code Playgroud)
你如何在 postgres 中表达这一点?
小智 6
SQL 不支持变量,这只能在过程语言中实现(在 Postgres 中,例如 PL/pgSQL)。
在普通 SQL 中实现此目的的方法是使用 CTE(这也是一个跨平台解决方案,不依赖于任何 SQL 方言):
with vars (foo) as (
values ('bar')
)
select foo
from vars;
Run Code Online (Sandbox Code Playgroud)
就像注入常量值一样,其中选择在从临时表复制时向插入表提供输入。
那么你不需要一个变量:
insert into target_table (c1, c2, c3)
select col_1, col_2, 'some value'
from staging_table;
Run Code Online (Sandbox Code Playgroud)
PostgreSQL 在允许使用变量的位置和方式方面并不那么灵活。与您想要完成的任务最接近的事情可能是将其包围在一个DO块中,如下所示:
DO $$
DECLARE foo TEXT;
BEGIN
foo := 'bar' ;
SELECT foo;
END $$;
Run Code Online (Sandbox Code Playgroud)
请注意,这取决于上下文,您可以在此StackOverflow 答案中找到更多信息。
此外,您可以创建一个声明变量并返回值的函数,如下所示:
CREATE FUNCTION example_function () RETURNS text AS '
DECLARE
-- Declare a constant integer with a
-- default value of 5.
five CONSTANT INTEGER := 5;
-- Declare an integer with a default
-- value of 100 that cannot be NULL.
ten INTEGER NOT NULL := 10;
-- Declare a character with
-- a default value of "a".
letter CHAR DEFAULT ''a'';
BEGIN
return letter;
END;
Run Code Online (Sandbox Code Playgroud)
有关此方法的更多信息请参见此处。