PostgreSQL 쿼리에서 변수를 선언하는 방법
PostgreSQL 8.3 쿼리에서 사용할 변수를 어떻게 선언합니까?MS SQL Server에서 다음을 수행 할 수 있습니다.
DECLARE @myvar INT
SET @myvar = 5
SELECT *
FROM somewhere
WHERE something = @myvar
PostgreSQL에서 동일한 작업을 수행하려면 어떻게합니까? 문서에 따르면 변수는 단순히 "이름 유형;"으로 선언되지만 구문 오류가 발생합니다.
myvar INTEGER;
누군가 나에게 올바른 구문의 예를 줄 수 있습니까?
PostgreSQL에는 이러한 기능이 없습니다. pl / PgSQL (또는 다른 pl / *)에서만 수행 할 수 있지만 일반 SQL에서는 수행 할 수 없습니다.예외는
WITH ()
변수 또는 변수로 작동 할 수있는 쿼리입니다
tuple
. 임시 값 테이블을 리턴 할 수 있습니다.
WITH master_user AS (
SELECT
login,
registration_date
FROM users
WHERE ...
)
SELECT *
FROM users
WHERE master_login = (SELECT login
FROM master_user)
AND (SELECT registration_date
FROM master_user) > ...;
나는
을 사용하여 동일한 목표를 달성했습니다. 아주 우아하지는 않지만 같은 일을 할 수는 없습니다. 이 예제에서는 정말 과잉입니다. 나는 또한 이것을 추천하지 않습니다.
WITH myconstants (var1, var2) as (
values (5, 'foo')
)
SELECT *
FROM somewhere, myconstants
WHERE something = var1
OR something_else = var2;
PLPGSQL에서 이것을 시도 할 수도 있습니다.
DO $$
DECLARE myvar integer;
BEGIN
SELECT 5 INTO myvar;
DROP TABLE IF EXISTS tmp_table;
CREATE TABLE tmp_table AS
SELECT * FROM yourtable WHERE id = myvar;
END $$;
SELECT * FROM tmp_table;
위의 Postgres 9.0 이상이 필요합니다.
클라이언트에 따라 다릅니다.그러나
psql
클라이언트를 사용하는 경우 다음을 사용할 수 있습니다.
my_db=> \set myvar 5
my_db=> SELECT :myvar + 1 AS my_var_plus_1;
my_var_plus_1
---------------
6
텍스트 변수를 사용하는 경우 인용해야합니다.
\set myvar 'sometextvalue'
select * from sometable where name = :'myvar';
동적 구성 설정
이를 위해 동적 구성 설정을 "남용"할 수 있습니다.
-- choose some prefix that is unlikely to be used by postgres
set session my.vars.id = '1';
select *
from person
where id = current_setting('my.vars.id')::int;
구성 설정은 항상 varchar 값이므로 사용할 때 올바른 데이터 유형으로 캐스트해야합니다. 이것은 모든 SQL 클라이언트
\set
에서 작동 하지만
psql
위의 Postgres 9.2 이상이 필요합니다.
For previous versions, the variable had to be declared in postgresql.conf
prior to being used, so it limited its usability somewhat. Actually not the variable completely, but the config "class" which is essentially the prefix. But once the prefix was defined, any variable could be used without changing postgresql.conf
Using a Temp Table outside of pl/PgSQL
Outside of using pl/pgsql or other pl/* language as suggested, this is the only other possibility I could think of.
begin;
select 5::int as var into temp table myvar;
select *
from somewhere s, myvar v
where s.something = v.var;
commit;
I want to propose an improvement to @DarioBarrionuevo's answer, to make it simpler leveraging temporary tables.
DO $$
DECLARE myvar integer = 5;
BEGIN
CREATE TEMP TABLE tmp_table ON COMMIT DROP AS
-- put here your query with variables:
SELECT *
FROM yourtable
WHERE id = myvar;
END $$;
SELECT * FROM tmp_table;
This solution is based on the one proposed by fei0x but it has the advantages that there is no need to join the value list of constants in the query and constants can be easily listed at the start of the query. It also works in recursive queries.
Basically, every constant is a single-value table declared in a WITH clause which can then be called anywhere in the remaining part of the query.
- Basic example with two constants:
WITH
constant_1_str AS (VALUES ('Hello World')),
constant_2_int AS (VALUES (100))
SELECT *
FROM some_table
WHERE table_column = (table constant_1_str)
LIMIT (table constant_2_int)
Alternatively you can use SELECT * FROM constant_name
instead of TABLE constant_name
which might not be valid for other query languages different to postgresql.
Here is an example using PREPARE statements. You still can't use ?
, but you can use $n
notation:
PREPARE foo(integer) AS
SELECT *
FROM somewhere
WHERE something = $1;
EXECUTE foo(5);
DEALLOCATE foo;
True, there is no vivid and unambiguous way to declare a single-value variable, what you can do is
with myVar as (select "any value really")
then, to get access to the value stored in this construction, you do
(select * from myVar)
for example
with var as (select 123)
... where id = (select * from var)
참고URL : https://stackoverflow.com/questions/1490942/how-to-declare-a-variable-in-a-postgresql-query
'programing' 카테고리의 다른 글
Flask for Python을 사용하여 방문자의 IP 주소 가져 오기 (0) | 2020.05.10 |
---|---|
Android 에뮬레이터에서 localhost : port에 액세스 (0) | 2020.05.10 |
R의 작업 공간에서 하나를 제외한 모든 객체를 제거하려면 어떻게합니까? (0) | 2020.05.10 |
git add, commit 및 push 명령을 하나로? (0) | 2020.05.10 |
{…} 시도가 마지막으로 {…} 좋은 이유는 무엇입니까? (0) | 2020.05.10 |