Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Creating Tables in Triggers/Functions

Status
Not open for further replies.

JWHardcastle

Programmer
Feb 17, 2003
3
US
I'm trying to use a pair of triggers and functions to generate a hierarchically sorted list of Locations based on a linear table. Basically, each location has a parent from within the locations table. I want to create an alphabetical list where children are listed after their parents. I've done this successfully on SQL server, but can't get it working on Postgres.

I have a trigger on the Locations table for AFTER UPDATE INSERT DELETE that generates the tree from scratch. The trigger just calls parsetree().

Code:
BEGIN
	CREATE TABLE "stack" (
	  locid INTEGER,
	  lvl SMALLINT
	) WITHOUT OIDS;
	
	DELETE FROM "lochier";

	CREATE TRIGGER "parse_tree_help" BEFORE INSERT OR UPDATE OR DELETE
	ON stack FOR EACH ROW
	EXECUTE PROCEDURE "parsetreehelp"();

	INSERT INTO "stack"(locid,lvl)
		SELECT LocID, 1
		FROM Locations
		WHERE ParentID IS NULL
		ORDER BY LocName;

    DROP TABLE "stack";

	RETURN NULL;
END;

Parsetree then calls parestreehelp():
Code:
BEGIN
	INSERT INTO lochier(locid, lvl)
	VALUES(NEW.locid, NEW.lvl);

	INSERT INTO "stack"
		SELECT LocID, NEW.lvl+1
		FROM Locations
		WHERE ParentID = NEW.locid
		ORDER BY LocName;
		
	RETURN NEW;
END;

If I create these functions in the right order, they work once, then immediately afteward claim that "relation 17xxx does not exist" where 17xxx is a number that is slowly going up everytime I try this.

Any ideas? I thought it might have something to do with stack, but quoting it didn't seem to help. Thanks in advance.
 
Hi JWHardcastle,

You might take a look at the postgres cookbook which has a number example functions and triggers. Maybe you will find something there that will give you an idea how to write your trigger.


LelandJ Leland F. Jackson, CPA
Software - Master (TM)
Nothing Runs Like the Fox
 
That's exactly what I was looking for and couldn't fine. Thanks!
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top