Store and reuse value returned by INSERT … RETURNING

… that can be used to insert values into other tables? You can even do that in a single SQL statement using a data-modifying CTE: WITH ins1 AS ( INSERT INTO tbl1(txt) VALUES (‘foo’) RETURNING tbl1_id ) INSERT INTO tbl2(tbl1_id) SELECT * FROM ins1 Requires PostgreSQL 9.1 or later. db<>fiddle here (Postgres 13) Old sqlfiddle … Read more

PostgreSQL: Query has no destination for result data

The stored procedure won’t just return the result of the last SELECT. You need to actually return the value: CREATE OR REPLACE FUNCTION fun() RETURNS text AS $$ BEGIN — …. RETURN(SELECT dblink_disconnect()); END $$ LANGUAGE plpgsql; You’re getting the error because Postgres expects the function to return something of type text, but your function … Read more

Select statement to return parent and infinite children

So referencing this answer: SQL Server CTE Parent Child recursive Here’s a working version with your schema: Table Creation Script CREATE TABLE YOUR_TABLE ([ID] int, [ParentID] int, [Name] varchar(21)) ; INSERT INTO YOUR_TABLE ([ID], [ParentID], [Name]) VALUES (1, NULL, ‘A root’), (2, NULL, ‘Another root’), (3, 1, ‘Child of 1’), (4, 3, ‘Grandchild of 1’), … Read more

How to create Temp table with SELECT * INTO tempTable FROM CTE Query

Sample DDL create table #Temp ( EventID int, EventTitle Varchar(50), EventStartDate DateTime, EventEndDate DatetIme, EventEnumDays int, EventStartTime Datetime, EventEndTime DateTime, EventRecurring Bit, EventType int ) ;WITH Calendar AS (SELECT /*…*/) Insert Into #Temp Select EventID, EventStartDate, EventEndDate, PlannedDate as [EventDates], Cast(PlannedDate As datetime) AS DT, Cast(EventStartTime As time) AS ST,Cast(EventEndTime As time) AS ET, EventTitle … Read more