programing

간단한 Postgre에서 변수를 사용하는 방법SQL 스크립트?

linuxpc 2023. 5. 1. 20:01
반응형

간단한 Postgre에서 변수를 사용하는 방법SQL 스크립트?

예를 들어 MS-SQL에서 조회 창을 열고 다음을 실행할 수 있습니다.

DECLARE @List AS VARCHAR(8)

SELECT @List = 'foobar'

SELECT *
FROM   dbo.PubLists
WHERE  Name = @List

PostgreSQL에서 이 작업은 어떻게 수행됩니까?할 수 있을까요?

전체 답변은 공식 Postgre에 있습니다.SQL 설명서.

새로운 PG9.0 익명 코드 차단 기능(http://www.postgresql.org/docs/9.1/static/sql-do.html )을 사용할 수 있습니다.

DO $$
DECLARE v_List TEXT;
BEGIN
  v_List := 'foobar' ;
  SELECT *
  FROM   dbo.PubLists
  WHERE  Name = v_List;
  -- ...
END $$;

마지막 삽입 ID도 얻을 수 있습니다.

DO $$
DECLARE lastid bigint;
BEGIN
  INSERT INTO test (name) VALUES ('Test Name') 
  RETURNING id INTO lastid;

  SELECT * FROM test WHERE id = lastid;
END $$;
DO $$
DECLARE  
   a integer := 10;  
   b integer := 20;  
   c integer;  
BEGIN  
   c := a + b;
    RAISE NOTICE'Value of c: %', c;
END $$;

사용할 수 있는 항목:

\set list '''foobar'''
SELECT * FROM dbo.PubLists WHERE name = :list;

그것으로 충분합니다

다음은 plpgsql에서 변수를 사용하는 예입니다.

create table test (id int);
insert into test values (1);
insert into test values (2);
insert into test values (3);

create function test_fn() returns int as $$
    declare val int := 2;
    begin
        return (SELECT id FROM test WHERE id = val);
    end;
$$ LANGUAGE plpgsql;

SELECT * FROM test_fn();
 test_fn 
---------
       2

자세한 내용은 plpgsql 문서를 참조하십시오.

그들이 사용하는 다른 문서들을 발견했습니다.\set스크립팅 변수를 선언하지만 그 값은 상수 값과 같은 것으로 보이며 상수 변수가 아닌 변수처럼 작용할 수 있는 방법을 찾고 있습니다.

예:

\set Comm 150

select sal, sal+:Comm from emp

여기서sal표 'sigma'에 존재하는 값입니다.comm상수 값입니다.

여기서 @nad2000의 답변과 @Pavel의 답변을 바탕으로 Flyway 마이그레이션 스크립트를 작성하게 되었습니다.데이터베이스 스키마를 수동으로 수정한 시나리오에 대한 처리.

DO $$
BEGIN
    IF NOT EXISTS(
        SELECT TRUE FROM pg_attribute 
        WHERE attrelid = (
            SELECT c.oid
            FROM pg_class c
            JOIN pg_namespace n ON n.oid = c.relnamespace
            WHERE 
                n.nspname = CURRENT_SCHEMA() 
                AND c.relname = 'device_ip_lookups'
            )
        AND attname = 'active_date'
        AND NOT attisdropped
        AND attnum > 0
        )
    THEN
        RAISE NOTICE 'ADDING COLUMN';        
        ALTER TABLE device_ip_lookups
            ADD COLUMN active_date TIMESTAMP;
    ELSE
        RAISE NOTICE 'SKIPPING, COLUMN ALREADY EXISTS';
    END IF;
END $$;

의 변수를 사용하는 경우(예: 테이블 변경):

DO $$ 
DECLARE name_pk VARCHAR(200);
BEGIN
select constraint_name
from information_schema.table_constraints
where table_schema = 'schema_name'
      and table_name = 'table_name'
      and constraint_type = 'PRIMARY KEY' INTO name_pk;
IF (name_pk := '') THEN
EXECUTE 'ALTER TABLE schema_name.table_name DROP CONSTRAINT ' || name_pk;

Postgresql에는 맨 변수가 없으므로 임시 테이블을 사용할 수 있습니다.변수는 코드 블록 또는 사용자 인터페이스 기능으로만 사용할 수 있습니다.

베어 변수가 필요한 경우 임시 테이블을 사용할 수 있습니다.

CREATE TEMP TABLE list AS VALUES ('foobar');

SELECT dbo.PubLists.*
FROM   dbo.PubLists,list
WHERE  Name = list.column1;

저는 이런 일을 해야만 했습니다.

CREATE OR REPLACE FUNCTION MYFUNC()
RETURNS VOID AS $$
DO
$do$
BEGIN
DECLARE
 myvar int;
 ...
END
$do$
$$ LANGUAGE SQL;

또한 실제 쿼리에서 사용하는 상수 쿼리를 만들 수도 있습니다.

WITH vars as (SELECT 'foobar' AS list) 
SELECT *
FROM   dbo.PubLists, vars
WHERE  Name = vars.list

인기와 다소 불완전한 답변을 감안하여 두 가지 해결책을 제시하겠습니다.

  1. 행을 반환하지 않는 Do 블록입니다.트랜잭션 커서로 행을 반환할 수 있지만, 조금 지저분합니다.
  2. 행을 반환하는 함수

아래에서는 오른쪽 아래 "블럽"에 있는 트윗을 "헬로 월드"로 업데이트하는 과도하게 구운 예를 사용하겠습니다.

id(클라이언트) pub_id(텍스트) 트윗(텍스트)
1 abc 안녕 세계
2 디프 흐느적거리다

간단한 작업 블록

do $$
declare
    src_pub_id text;
    dst_pub_id text;
    src_id    int; 
    dest_id   int;
    src_tweet text;
begin
    src_pub_id := 'abc';
    dst_pub_id := 'def';
    
    -- query result into a temp variable
    src_id := (select id from tweets where pub_id = src_pub_id);

    -- query result into a temp variable (another way)
    select tweet into src_tweet from tweets where id = src_id;

    dest_id := (select id from tweets where pub_id = dst_pub_id);
    update tweets set tweet=src_tweet where id = dest_id;
end $$ language plpgsql; -- need the language to avoid ERROR 42P13

A 함수

create or replace function sync_tweets(
    src_pub_id text, -- function arguments
    dst_pub_id text
) returns setof tweets as -- i.e. rows. int, text work too
$$
declare
    src_id    int; -- temp function variables (not args)
    dest_id   int;
    src_tweet text;
begin
    -- query result into a temp variable
    src_id := (select id from tweets where pub_id = src_pub_id);

    -- query result into a temp variable (another way)
    select tweet into src_tweet from tweets where id = src_id;

    dest_id := (select id from tweets where pub_id = dst_pub_id);
    update tweets set tweet=src_tweet where id = dest_id;

    return query -- i.e. rows, return 0 with return int above works too
        select * from tweets where pub_id in (src_pub_id, dst_pub_id);
end
$$ language plpgsql; -- need the language to avoid ERROR 42P13

-- Run it!
select * from sync_tweets('abc', 'def');

-- Optional drop if you don't want the db to keep your function
drop function if exists sync_tweets(text, text);

/*
  Outputs
   __________________________________________________ 
  |  id (serial)  |  pub_id (text)  |  tweet (text)  |
  |---------------|-----------------|----------------|
  |  1            |  abc            |  hello world   |
  |  2            |  def            |  blurb         |
  --------------------------------------------------
*/

언급URL : https://stackoverflow.com/questions/766657/how-do-you-use-variables-in-a-simple-postgresql-script

반응형