Consider this T-SQL:
DECLARE @ColorID INT
SET @ColorID = 3
SELECT *, left(name,3)
FROM Products p
WHERE ColorID = @ColorID
This works but doesn't declare a variable:
SELECT *, substring(name,1,3)
FROM Products p
WHERE ColorID = 3
I tried this:
DO $$
DECLARE ColorID INT;
BEGIN
ColorID := 3;
SELECT *, substring(name,1,3)
FROM Products p
WHERE ColorID = ColorID
END$$;
It wants me to specify the result set. I don't want to do that because it keeps changing as I'm just exploring the data.
ERROR: query has no destination for result data
I tried "return query" but then get this error:
ERROR: cannot use RETURN QUERY in a non-SETOF function
So I want to return multiple rows without specifying what the result set should look like. Using PostgreSQL 9.4.4
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)Use a temporary table for variables:
Use a temporary table for results:
Create a function (example):