Anonymous code block (DO
command) cannot return rows and Postgres has no global variables.
There are few ways to live without it. Four of them are as follows.
Use common table expression (WITH
command)
WITH def AS (
SELECT 3 AS colorid
)
SELECT *, substring(name,1,3)
FROM products
JOIN def
USING (colorid);
Use a temporary table for variables:
CREATE TEMP TABLE var(colorid int);
INSERT INTO var values (3);
SELECT *, substring(name,1,3)
FROM products
JOIN var
USING (colorid);
DROP TABLE var;
Use a temporary table for results:
DO $$
DECLARE v_colorid INT;
BEGIN
v_colorid := 3;
CREATE TEMP TABLE res AS
SELECT *, substring(name,1,3)
FROM products
WHERE colorid = v_colorid;
END $$;
SELECT *
FROM res;
DROP TABLE res;
Create a function (example):
CREATE OR REPLACE FUNCTION select_from_products()
RETURNS TABLE (colorid int, name text, abbr text)
LANGUAGE plpgsql as $$
DECLARE v_colorid INT;
BEGIN
v_colorid := 3;
RETURN QUERY
SELECT *, substring(p.name,1,3)
FROM products p
WHERE p.colorid = v_colorid;
END $$;
SELECT * FROM select_from_products();
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…