I am facing a problem, I have developed a function with dynamic whare clause.
When every I run the query separatly it returns the value much faster while running with EXECUTE it give allot of time. "cv."SessionId" = ''f0d1c0e1-b13c-4aff-b1f7-432183b06d10'' AND cv."CampusId" = ''4f4310a3-9c36-49c2-8456-5604cb7e9a62'' AND cv."ProgramId"=''e50efffa-40a3-4eb9-a65b-65106967add7'' AND cv."ShiftId"=''414de073-ca8b-4a84-80bc-52c2030b4eeb'' AND cv."ProgramDetailId"=''8d1ce321-d015-4336-ba92-dcd2c8b6443b'' AND cv."ClassId"=''8931d744-acc9-4776-a03a-2b705038ea48'' AND cv."SectionId"=''83c507d0-8f61-4a28-b221-88625482953f'' AND cv."CollectorId"=''e58d2fbf-839a-49a1-b1ce-92e7c26a305b'' AND cv."FeeHeadId"=''5721bc8f-4e9c-49d0-a992-6b846fafb9db'' AND cv."PaidDate" >= ''2020-07-01'' AND cv."PaidDate" <= ''2020-08-07'' ORDER BY cv."ChallanNo" ASC" this is where clause parameter which change every time. some time two some time four or five. the following is my function which i want to optimize.
declare feeheadrow record;
declare paiddate date;
declare rollno text;
declare admisformid uuid;
declare feeheadname text;
declare instNo int4;
declare stdname text;
declare fathername text;
declare refno text;
declare classid uuid;
declare campusprogid uuid;
declare stdid uuid;
declare challano text;
declare campusid uuid;
declare sessionid uuid;
declare progdetailid uuid;
declare campusname text;
declare descrip text;
declare shiftname text;
declare genderid uuid;
declare shiftid uuid;
declare remarks text;
declare sessionname text;
declare totalamount int4;
declare programid uuid;
declare collectorid uuid;
BEGIN
DROP TABLE IF EXISTS "FeeReport";
DROP TABLE IF EXISTS "FeeHeads";
create temp table "FeeReport"("NewID" uuid, "PaidDate" Date, "RollNo" text, "AdmissionFormId" uuid, "FeeHeadName" text, "InstallmentNo" int4, "StudentName" text, "FatherName" text, "RefferenceNo" text, "ClassId" uuid, "CampusProgramId" uuid, "FeeHeadId" uuid,
"FeeAmount" int4, "PayableAmount" int4, "StudentId" uuid, "ChallanNo" text, "CampusId" uuid, "SessionId" uuid,
"ProgramDetailId" uuid, "CampusName" text, "Description" text, "ShiftName" text, "GenderId" uuid,
"ShiftId" uuid,"Remarks" text, "ScholarshipCriteriaId" uuid, "ScholarshipCriteriaName" text, "SessionName" text, "TotalAmount" int4
, "ProgramId" uuid, "CollectorId" uuid
) on commit DROP;
create temp table "FeeHeads"("FeeHeadId" UUID, "FullName" TEXT) on commit drop;
insert into "FeeReport"
SELECT * FROM "Query"('cv.*', '"Fee"."VWFeeStatement2" AS cv', whereclause) AS
"FeeRecords" ("NewID" uuid, "PaidDate" date, "RollNo" text, "AdmissionFormId" uuid, "FeeHeadName" text, "InstallmentNo" int4, "StudentName" text, "FatherName" text, "RefferenceNo" text, "ClassId" uuid, "CampusProgramId" uuid, "FeeHeadId" uuid, "FeeAmount" int4, "PayableAmount" int4, "StudentId" uuid, "ChallanNo" text, "CampusId" uuid, "SessionId" uuid, "ProgramDetailId" uuid, "CampusName" text, "Description" text, "ShiftName" text, "GenderId" uuid, "ShiftId" uuid, "Remarks" text, "ScholarshipCriteriaId" uuid, "ScholarshipCriteriaName" text, "SessionName" text, "TotalAmount" int4,"ProgramId" uuid,"CollectorId" uuid);
insert into "FeeReport"
SELECT * FROM "Query"('cv.*', '"Fee"."VWFeeStatementOther2" AS cv', whereclause) AS
"FeeRecords" ("NewID" uuid, "PaidDate" date, "RollNo" text, "AdmissionFormId" uuid, "FeeHeadName" text, "InstallmentNo" int4, "StudentName" text, "FatherName" text, "RefferenceNo" text, "ClassId" uuid, "CampusProgramId" uuid, "FeeHeadId" uuid, "FeeAmount" int4, "PayableAmount" int4, "StudentId" uuid, "ChallanNo" text, "CampusId" uuid, "SessionId" uuid, "ProgramDetailId" uuid, "CampusName" text, "Description" text, "ShiftName" text, "GenderId" uuid, "ShiftId" uuid, "Remarks" text, "ScholarshipCriteriaId" uuid, "ScholarshipCriteriaName" text, "SessionName" text, "TotalAmount" int4,"ProgramId" uuid,"CollectorId" uuid);
insert into "FeeHeads"
SELECT DISTINCT fh."FeeHeadId", fh."FullName" FROM "Fee"."FeeHead" AS fh, "FeeReport" fr
WHERE fr."FeeHeadId" = fh."FeeHeadId";
FOR vwfeestatementrow in select distinct f."AdmissionFormId"
from "FeeReport" f
LOOP
select vw."PaidDate", vw."RollNo", vw."AdmissionFormId", vw."InstallmentNo", vw."StudentName", vw."FatherName" , vw."RefferenceNo", vw."ClassId",
vw."CampusProgramId", vw."StudentId", vw."ChallanNo", vw."CampusId" , vw."SessionId",
vw."ProgramDetailId", vw."CampusName", vw."Description", vw."ShiftName", vw."GenderId",vw."ShiftId", vw."SessionName", vw."TotalAmount",vw."ProgramId",vw."CollectorId"
INTO paiddate,rollno,
admisformid,instNo,stdname,fathername,refno,classid,
campusprogid,stdid,challano,campusid,sessionid,progdetailid,campusname,descrip,shiftname,genderid,shiftid,sessionname,totalamount,programid,collectorid
from "FeeReport" vw where vw."AdmissionFormId"=vwfeestatementrow."AdmissionFormId" limit 1;
FOR feeheadrow IN SELECT fh."FeeHeadId",fh."FullName" FROM "FeeHeads" fh WHERE (fh."FeeHeadId" NOT IN (
SELECT ins."FeeHeadId" FROM "FeeReport" AS ins WHERE ins."AdmissionFormId" = vwfeestatementrow."AdmissionFormId"))
LOOP
INSERT INTO "FeeReport"("NewID","PaidDate","RollNo","AdmissionFormId","FeeHeadName","InstallmentNo","StudentName",
"FatherName","RefferenceNo","ClassId", "CampusProgramId","FeeHeadId",
"FeeAmount", "PayableAmount", "StudentId", "ChallanNo", "CampusId", "SessionId",
"ProgramDetailId", "CampusName", "Description", "ShiftName", "GenderId",
"ShiftId","Remarks", "ScholarshipCriteriaId", "ScholarshipCriteriaName", "SessionName", "TotalAmount","ProgramId",
"CollectorId"
)
VALUES(uuid_generate_v1(),paiddate,rollno,vwfeestatementrow."AdmissionFormId",
feeheadrow."FullName",instNo,stdname,fathername
,refno,classid,campusprogid,feeheadrow.
"FeeHeadId",0,0,stdid,challano,campusid,
sessionid,progdetailid,campusname,descrip,shiftname,genderid,shiftid,'',null,'',
sessionname,totalamount,programid,collectorid
);
END LOOP;
END LOOP;
-- DELETE FROM "Student" AS st WHERE st."AdmissionFormId" IN (SELECT af."AdmissionFormId" FROM "Fee"."StudentFeeStructure" AS sf, "Admission"."AdmissionForm" AS af WHERE sf."AdmissionFormId" = af."AdmissionFormId" AND af."CampusProgramId" = campusprogramid AND sf."ConcessionDetailId" IS NOT NULL);
RETURN query Select fr.* from "FeeReport" as fr ORDER BY fr."ChallanNo", fr."FeeHeadName";
END```
Related
I have this stored procedure in PostgreSQL where I want to make an insert in a table. I get some parameters from the procedure and using them I have tried to select other attributes on other tables.
This is my stored procedure:
CREATE OR REPLACE FUNCTION "public"."prc_sales_invoice_header_insert"("customercode" varchar, "sales_note" varchar, "automatic_payment_id" int4, "cash_register_code" varchar,...etc)
RETURNS "pg_catalog"."void" AS $BODY$
--declaring variables to store data from the tables
DECLARE
salesdate date;
salesdocumentserial varchar;
currencycode varchar;
currencycode2 varchar;
customername varchar;
warehousecode varchar;
......etc.
BEGIN
--getting values from tables and storing to variables
SELECT "name" into customername from public."customers" where "customer_code" = customercode;
SELECT CURRENT_DATE into salesdate;
SELECT max(sales_invoice_header_id) into salesdocumentserial from public."sales_invoice_header";
.....
--inserting values
INSERT INTO public."sales_invoice_header"("sales_date",
"sales_document_serial",
"currency_code",
"currency_code2",
"customer_code",
....
VALUES(
salesdate,
salesdocumentserial,
currencycode,
currencycode2,
customer_code,
.....)
END
$BODY$
LANGUAGE plpgsql VOLATILE
COST 100
When I try to execute it throws an error saying:
"ERROR: column "customer_code" does not exist", "HINT: There is a column named "customer_code" in table "sales_invoice_header", but it cannot be referenced from this part of the query."
Table customers exists and there is a column named costomer_code but I don't understand why it cannot reference it.
Table customers:
-- ----------------------------
-- Table structure for customers
-- ----------------------------
DROP TABLE IF EXISTS "public"."customers";
CREATE TABLE "public"."customers" (
"customer_id" int4 NOT NULL DEFAULT nextval('"Customers_CustomerId_seq"'::regclass),
"customer_code" varchar COLLATE "pg_catalog"."default",
"barcode" varchar COLLATE "pg_catalog"."default",
"qr_code" varchar COLLATE "pg_catalog"."default",
"tax_id" varchar COLLATE "pg_catalog"."default",
"business_id" varchar COLLATE "pg_catalog"."default",
"city_id" int8,
"mobile" varchar COLLATE "pg_catalog"."default",
"accounting_number" varchar COLLATE "pg_catalog"."default",
"name" varchar COLLATE "pg_catalog"."default"
);
Can anyone help me with this, what I am doing wrong? Or is this the correct way of doing things?
Thanks in advance.
INSERT INTO public."sales_invoice_header"("sales_date",
"sales_document_serial",
"currency_code",
"currency_code2",
"customer_code",
....
VALUES(
salesdate,
salesdocumentserial,
currencycode,
currencycode2,
customer_code,
here customer_code is not a variable, nor literal - it is a column name. yet you don't select it form table - you try to use it in VALUES - won't work. either use
insert into ... select ...,customer_code from sales_invoice_header
or
insert into ... values(..., VAR_customer_code)
or
insert into ... values(..., 'value_customer_code')
edit:
as a_horse_with_no_name noticed my VAR_customer_code, must be your customercode first argument?..
I have wrote a stored-procedure in PostgreSQL as an API to create contract and user in a same time (by postgrest).
CREATE OR REPLACE FUNCTION
auth.create_contracts(
username text,
password text,
services json,
province text,
region text,
type user_group,
telephone text,
mobile text,
email text,
start_date text,
end_date text,
organization_name text,
contract_number text,
name text,
economy_code INTEGER,
t_name text,
t_phone text,
t_ip text,
t_email text,
t_telephone text,
t_prefer_contract text,
area_state text,
area_city text,
area_county text
) RETURNS json
LANGUAGE plpgsql
AS $$
DECLARE
_user_id INTEGER;
_res json;
_now DOUBLE PRECISION;
_app_token text;
_username text;
BEGIN
SELECT random_string(64) INTO _app_token;
INSERT INTO auth.users(
username,
password,
role,
services,
app_token,
province,
region,
type,
phone,
organization_name,
mobile,
email
)
VALUES (
username,
password,
username,
services,
_app_token,
province,
region,
type,
telephone,
organization_name,
mobile,
email
);
SELECT username INTO _username;
SELECT id FROM auth.users WHERE users.username=_username
INTO _user_id;
INSERT INTO auth.contracts(
user_id,
start_date,
end_date,
organization_name,
contract_number,
economy_code,
t_name,
t_phone,
t_ip,
t_email,
t_telephone,
t_prefer_contract,
name,
area_state,
area_city,
area_county
)
VALUES(
_user_id,
start_date::TIMESTAMP,
end_date::TIMESTAMP,
organization_name,
contract_number,
economy_code,
t_name,
t_phone,
t_ip,
t_email,
t_telephone,
t_prefer_contract,
name,
area_state,
area_city,
area_county
);
SET TIME ZONE 'UTC-3:32';
PERFORM (
SELECT auth.contract_redis_function(end_date::TIMESTAMP, now()::TIMESTAMP,
_app_token, username, 100000)
);
SELECT json_build_object(
'status', 'ok',
'app_token', _app_token
)
INTO _res;
RETURN _res;
END;
$$;
users definition:
create table auth.users
(
id serial not null
constraint users_pkey
primary key,
username text,
password text,
role text,
services json,
app_token text,
province text,
region text,
type user_group,
contract_id integer,
phone text,
picture text,
is_first_login boolean default true,
is_locked boolean default false,
is_active boolean default true,
organization_name text,
mobile text,
email text,
prefer_contact text
)
;
create unique index users_username_uindex
on users (username);
contracts definition:
create table auth.contracts
(
user_id integer
constraint unique_contract
unique
constraint contract_user_01
references auth.users,
start_date timestamp,
end_date timestamp,
organization_name text,
contract_number text,
economy_code integer,
t_name text,
t_phone text,
t_ip text,
t_email text,
t_telephone text,
t_prefer_contract text,
area_state text,
area_city text,
area_county text,
name text,
id serial not null,
is_active boolean default true
);
I have a unique constraint on a key of users relation (id that is auto incremented)
sometimes when call the end-point raise an exception that key exists, but doesn't, and create record.
I don't know why!?
I have a similar problem when creating policy in a stored-procedure.
username is not unique in auth.users, so there is no guarantee that this query gets the correct id:
SELECT id FROM auth.users WHERE users.username=_username
INTO _user_id;
You will get the id of one of the rows with that username.
If there are several such rows, you could get the wrong one, and the UNIQUE constraint on contracts will be violated when you insert the same number a second time.
The solution is to always get the correct id like this:
INSERT INTO auth.users (...) VALUES (...)
RETURNING id INTO _user_id;
Then you will always get the id of the record you just inserted.
I really need advice. I'm trying to use the function : pivot_subrecords_set_table_1
In the following query:
SELECT rec.id AS key,
rec.primaryurn AS urn,
rec.mx_syscreatedby AS creared_by,
(SELECT mf_mxdate_str_to_date (epi.mx_epizoddate)) AS date_of_creation,
epi.mx_epizodenotes AS notes,
epi.mx_effectscountry AS country,
epi.mx_effectsregion AS region,
epi.mx_effectscity AS city,
(SELECT get_epizod_subrecords (epi.id)) AS epizod_type
(pivot_subrecords_set_table_1 (epi.id)).idx,
(pivot_subrecords_set_table_1 (epi.id)).upn_1 AS upn_1,
(pivot_subrecords_set_table_1 (epi.id)).status_1
FROM mxt_recordheader AS rec, mt_epizod AS epi, mt_epizod_subrecord AS eps
WHERE rec.entitytype = 'epizod'
AND rec.logicalserverprefix = 'EA'
AND epi.id = rec.id;
The function looks like this:
CREATE OR REPLACE FUNCTION public.pivot_subrecords_set_table_1(id bigint,
OUT idx bigint, OUT upn_1 text, OUT status_1 text, OUT upn_2 text, OUT
status_2 text, OUT upn_3 text, OUT status_3 text, OUT upn_4 text, OUT
status_4 text, OUT upn_5 text, OUT status_5 text, OUT upn_6 text, OUT
status_6 text, OUT upn_7 text, OUT status_7 text, OUT upn_8 text, OUT
status_8 text, OUT upn_9 text, OUT status_9 text, OUT upn_10 text, OUT
status_10 text)
RETURNS SETOF record
LANGUAGE plpgsql
AS $function$
DECLARE
key ALIAS FOR $1;
BEGIN
RETURN QUERY
WITH sub_upn AS (SELECT * FROM crosstab
('SELECT id, mx_osobastatus, mx_osobaupn FROM mt_epizod_subrecord
WHERE mt_epizod_subrecord.mx_syscategory = ''tableepizodinfo''
AND mt_epizod_subrecord.id = '|| key ||' GROUP BY id, mx_osobaupn,
mx_osobastatus
ORDER BY id') AS ct
(id bigint, UPN_1 text, UPN_2 text, UPN_3 text, UPN_4 text, UPN_5 text, UPN_6
text, UPN_7 text, UPN_8 text ,UPN_9 text, UPN_10 text)
),
sub_stat AS
(SELECT * FROM crosstab
('SELECT id, mx_osobaupn, mx_osobastatus FROM mt_epizod_subrecord
WHERE mt_epizod_subrecord.mx_syscategory = ''tableepizodinfo''
AND mt_epizod_subrecord.id = '|| key ||' GROUP BY 1,2,3 ORDER BY id ')
AS cn (id bigint, status_1 text, status_2 text, status_3 text, status_4 text,
status_5 text, status_6 text, status_7 text, status_8 text,
status_9 text, status_10 text)
)
SELECT
supn.id,
supn.UPN_1,
sust.status_1,
supn.UPN_2,
sust.status_2,
supn.UPN_3,
sust.status_3,
supn.UPN_4,
sust.status_4,
supn.UPN_5,
sust.status_5,
supn.UPN_6,
sust.status_6,
supn.UPN_7,
sust.status_7,
supn.UPN_8,
sust.status_8,
supn.UPN_9,
sust.status_9,
supn.UPN_10,
sust.status_10
FROM sub_upn supn
JOIN sub_stat sust ON supn.id = sust.id;
END;
$function$
But the performance of the function is very low.
How can I increase the performance of a function or can I rewrite the query in which it is used?
Use plprofiler to figure out what is slow in your function and optimize that.
I am creating a function which creates well, but when I call it there is issue.
CREATE OR REPLACE FUNCTION public.winner_pagination(
_searchText varchar,
_sort varchar, _order char(3), _limit int, _offset int)
RETURNS SETOF RECORD AS
$BODY$
DECLARE
BEGIN
RETURN QUERY SELECT CREATED_DATE as createddate, DELETED AS deleted, FIRST_NAME AS firstname, LAST_NAME AS lastname,
NO_OF_AWARDS AS noofawards, PHONE AS phone, COUNTRY_ID AS country, ORGId_ID AS orgId , EMAIL as email
FROM winner
WHERE deleted = false
and ORGId_ID = 1
and first_name LIKE _searchText OR last_name LIKE _searchText OR email LIKE _searchText OR phone LIKE _searchText
order by _sort limit _limit offset _offset;
END;$BODY$
LANGUAGE plpgsql VOLATILE
COST 100;
ALTER FUNCTION public.winner_pagination(varchar, varchar, char(3), int, int)
OWNER TO postgres;
I am calling the function like this
select * from winner_pagination('Arthur', 'firstname', 'asc', 9, 0)
as f(createddate date, deleted boolean, firstname varchar, lastname varchar, noofawards integer ,
phone varchar, country integer, orgId integer, email varchar ) ;
ERROR: structure of query does not match function result type
SQL state: 42804
Detail: Returned type timestamp without time zone does not match expected type date in column 1.
Context: PL/pgSQL function winner_pagination(character varying,character varying,character,integer,integer) line 6 at RETURN QUERY
Three Postgresql tables (Windows V 9.1.3)
The table obx is a dynamic table that recieves data from several machines.
We want to produce an after insert trigger function
The table testcode is a fixed table, which contains values we are trying to match to the obx table. If testcode TestID an integer field is not null, we want to insert the data into a new table finaldata using an after insert trigger on the table obx.
The first trigger works, but it produces duplicate data. The trigger has to contain "LIMIT 3" as one of the machines send three results at a time.
Trying second option using SQL only but not working.
The fields marked XY in the table finaldata are for internal use.
CREATE TABLE "public"."obx" (
"obxID" serial primary key,
"Pid" varchar,
"Sid" varchar,
"SidOrig" varchar,
"Parameter" varchar,
"Result" varchar,
"ResultOrig" varchar,
"Units" varchar,
"RefRange" varchar,
"Flag" varchar,
"FlagOrig" varchar,
"OperatorID" varchar,
"ObsTime" char(14),
"MsgTime" char(14),
"UnixTime" int4,
"Analyzer" varchar,
"Segment" varchar
)
;
CREATE TABLE "public"."testcode" (
"TcodeID" serial primary key,
"Analyzer" varchar,
"Parameter" varchar,
"TestName" varchar,
"ShortTestName" varchar,
"TestID" int4
)
;
CREATE TABLE "public"."finaldata" (
"FdataID" serial primary key,
"Pid" varchar,
"Sid" varchar,
"SidOrig" varchar,
"Parameter" varchar,
"Result" varchar,
"ResultOrig" varchar,
"Units" varchar,
"OperatorID" varchar,
"ObsTime" varchar,
"MsgTime" varchar,
"Analyzer" varchar,
"TestName" varchar,
"ShortTestName" varchar,
"TestID" varchar,
"XYchar1" varchar,
"XYchar2" varchar,
"XYchar3" varchar,
"XYint1" int4,
"XYint2" int4,
"XYint3" int4,
"XYGuid" uuid
)
;
DECLARE
var INTEGER;
name text;
short text;
id integer;
BEGIN
SELECT count("TestID") from testcode WHERE "testcode"."Parameter" = NEW."Parameter" into var;
IF var > 0 THEN
SELECT "TestName", "ShortTestName", "TestID" from testcode where "Parameter" = NEW."Parameter" Limit 1 into name, short, id;
INSERT INTO finaldata ("Pid", "Sid", "SidOrig", "Parameter", "Result", "ResultOrig", "Units", "OperatorID", "ObsTime", "MsgTime", "Analyzer", "TestName", "ShortTestName", "TestID")
SELECT "Pid", "Sid", "SidOrig", "Parameter", "Result", "ResultOrig", "Units", "OperatorID", "ObsTime", "MsgTime", "Analyzer", name, short, id
from obx WHERE "obx"."Parameter" = NEW."Parameter"
LIMIT 3;
END if;
RETURN NEW;
END;
----------------------------
-- Triggers structure for table "public"."obx"
-- ----------------------------
CREATE TRIGGER finaldata_ins
AFTER INSERT ON obx
FOR EACH ROW
EXECUTE PROCEDURE testcode_matches()
;
CREATE FUNCTION testcode_matches()
RETURNS TRIGGER AS $meat$
BEGIN
INSERT INTO finaldata ("Pid", "Sid", "SidOrig", "Parameter", "Result", "ResultOrig", "Units", "OperatorID", "ObsTime", "MsgTime", "Analyzer", "TestName", "ShortTestName", "TestID")
SELECT "obx"."Pid", "obx"."Sid", "obx"."SidOrig", "obx"."Parameter", "obx"."Result", "obx"."ResultOrig", "obx"."Units", "obx"."OperatorID", "obx"."ObsTime", "obx"."MsgTime", "obx"."Analyzer", "TestName", "ShortTestName", "TestID"
FROM obx testcode
JOIN obx ON "obx"."Parameter" = "testcode"."Parameter"
WHERE "testcode"."Parameter" = NEW."Parameter"
AND "testcode"."TestID" = NEW."TestID"
;
RETURN NEW;
END;
$meat$
LANGUAGE plpgsql;
----------------------------
-- Triggers structure for table "public"."obx"
-- ----------------------------
CREATE TRIGGER finaldata_ins
AFTER INSERT ON obx
FOR EACH ROW
EXECUTE PROCEDURE testcode_matches()
;
It seems you were confusing yourself by giving obx the correlation name "testcode" :
TESTTABLES:
SET search_path='tmp';
DROP TABLE "obx" CASCADE;
CREATE TABLE "obx" (
"obxID" serial primary key,
"Pid" varchar,
"Sid" varchar,
"SidOrig" varchar,
"Parameter" varchar,
"Result" varchar,
"ResultOrig" varchar,
"Units" varchar,
"RefRange" varchar,
"Flag" varchar,
"FlagOrig" varchar,
"OperatorID" varchar,
"ObsTime" char(14),
"MsgTime" char(14),
"UnixTime" int4,
"Analyzer" varchar,
"Segment" varchar
);
DROP TABLE "testcode" CASCADE;
CREATE TABLE "testcode" (
"TcodeID" serial primary key,
"Analyzer" varchar,
"Parameter" varchar,
"TestName" varchar,
"ShortTestName" varchar,
"TestID" int4
) ;
DROP TABLE "finaldata" CASCADE;
CREATE TABLE "finaldata" (
"FdataID" serial primary key,
"Pid" varchar,
"Sid" varchar,
"SidOrig" varchar,
"Parameter" varchar,
"Result" varchar,
"ResultOrig" varchar,
"Units" varchar,
"OperatorID" varchar,
"ObsTime" varchar,
"MsgTime" varchar,
"Analyzer" varchar,
"TestName" varchar,
"ShortTestName" varchar,
"TestID" varchar,
"XYchar1" varchar,
"XYchar2" varchar,
"XYchar3" varchar,
"XYint1" int4,
"XYint2" int4,
"XYint3" int4,
"XYGuid" uuid
) ;
Function && trigger:
DROP FUNCTION testcode_matches() CASCADE;
CREATE FUNCTION testcode_matches()
RETURNS TRIGGER AS $meat$
BEGIN
INSERT INTO finaldata ("Pid", "Sid", "SidOrig", "Parameter", "Result", "ResultOrig", "Units"
, "OperatorID", "ObsTime", "MsgTime", "Analyzer", "TestName", "ShortTestName", "TestID")
SELECT ob."Pid", ob."Sid", ob."SidOrig", ob."Parameter", ob."Result", ob."ResultOrig", ob."Units"
, ob."OperatorID", ob."ObsTime", ob."MsgTime", ob."Analyzer"
, tc."TestName", tc."ShortTestName", tc."TestID"
FROM obx ob
JOIN testcode tc ON ob."Parameter" = tc."Parameter"
WHERE ob."Parameter" = NEW."Parameter"
-- AND ob."TestID" = NEW."TestID" -- Column does not exist
AND ob."obxID" = NEW."obxID" -- This appears to be the PK for obx
;
RETURN NEW;
END;
$meat$ LANGUAGE plpgsql;
CREATE TRIGGER finaldata_ins
AFTER INSERT ON obx
FOR EACH ROW
EXECUTE PROCEDURE testcode_matches()
;
TESTDATA:
INSERT INTO testcode ("TestID", "Parameter") VALUES ( 101, 'Fudge');
INSERT INTO obx -- i"obxID" serial primary key,
( "Pid", "Sid" , "Parameter" ) VALUES ('Foo', 'Bar' ,'Fudge' ) ;
SELECT * FROM finaldata;
Also: I am missing a few foreign key constraints. I would expect the testdata to have at least the same keyfields as obx as candidate key. (plus som version/date,Parameter keyfield) It seems your datamodel is not fit to support the data you feed into it.