考虑这个T-sql:
DECLARE @ColorID INT SET @ColorID = 3 SELECT *,left(name,3) FROM Products p WHERE ColorID = @ColorID
这有效但不声明变量:
SELECT *,substring(name,1,3) FROM Products p WHERE ColorID = 3
我试过这个:
DO $$ DECLARE ColorID INT; BEGIN ColorID := 3; SELECT *,3) FROM Products p WHERE ColorID = ColorID END$$;
它要我指定结果集.我不想这样做,因为它不断改变,因为我只是在探索数据.
ERROR: query has no destination for result data
ERROR: cannot use RETURN QUERY in a non-SETOF function
所以我想返回多行而不指定结果集应该是什么样子.使用Postgresql 9.4.4
匿名代码块(
没有它,没有什么方法可以生存.其中四个如下.
DO
command)无法返回行,Postgres没有全局变量.
没有它,没有什么方法可以生存.其中四个如下.
使用公用表表达式(WITH
command)
WITH def AS ( SELECT 3 AS colorid ) SELECT *,3) FROM products JOIN def USING (colorid);
对变量使用临时表:
CREATE TEMP TABLE var(colorid int); INSERT INTO var values (3); SELECT *,3) FROM products JOIN var USING (colorid); DROP TABLE var;
使用临时表来获得结果:
DO $$ DECLARE v_colorid INT; BEGIN v_colorid := 3; CREATE TEMP TABLE res AS SELECT *,3) FROM products WHERE colorid = v_colorid; END $$; SELECT * FROM res; DROP TABLE res;
创建一个函数(示例):
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,3) FROM products p WHERE p.colorid = v_colorid; END $$; SELECT * FROM select_from_products();