Postgresql error more than one row returned by a subquery when I used trigger - postgresql

I am using trigger and function to insert values into another table.
I do have this table
1)EXHIBITION
exhid exhname description strtdate enddate status
101 The Famous BLAH BLAH 2013-07-15 2013-10-13 SOON
102 York Exhibition BLAH BLAH 2013-08-07 2014-01-19 End
103 Fine ART BLAH BLAH 2014-09-26 2015-03-21 SOON
2)Works_Exhibitions
alphid numberid exhid
SCFI 1007 101
SCBU 1008 101
PAHF 1002 103
PAHE 1003 103
PASP 1004 103
and third empty table which has same attributes as Works_Exhibitions and name it Temp_works_exhibitions
alphid numberid exhid
I did create this function and trigger so once I update the status of any exhibition in the Exhibition table to be 'End', I would like to copy all the works of that exhibition to be in the new table Temp_works_exhibitions and then remove it from the Works_exhibition table
CREATE OR REPLACE FUNCTION add2Temp_works_exhibitions() returns TRIGGER AS $updExhibStat$
BEGIN
IF(NEW.Status = 'End') THEN
INSERT INTO temp_works_exhibitions
select
Works_Exhibitions.alphID,
Works_Exhibitions.numberID,
Works_Exhibitions.exhID
from
Works_Exhibitions
where
Works_Exhibitions.exhID = (select Exhibitions.exhID from Exhibitions where Exhibitions.Status = 'End');
delete from Works_Exhibitions where Works_Exhibitions.exhID = (select Exhibitions.exhID from Exhibitions where Exhibitions.Status = 'End');
RETURN NEW;
END IF;
RETURN NULL;
END;
$updExhibStat$ LANGUAGE plpgsql;
--CREATE TRIGGER updExhibStat AFTER UPDATE ON Exhibitions FOR EACH ROW EXECUTE PROCEDURE add2Temp_works_exhibitions();
When I test it first time it did work but when I tried to update a new exhibition I got this ERROR
ERROR: more than one row returned by a subquery used as an expression
CONTEXT: SQL statement "INSERT INTO temp_works_exhibitions
select
Works_Exhibitions.alphID,
Works_Exhibitions.numberID,
Works_Exhibitions.exhID
from
Works_Exhibitions
where
Works_Exhibitions.exhID = (select Exhibitions.exhID from Exhibitions where Exhibitions.Status = 'End')"
PL/pgSQL function add2temp_works_exhibitions() line 5 at SQL statement
Any Idea how to fix this

I guess I did fix the problem
I did add this command at the end of the function
UPDATE Exhibitions set Status = 'Expired' where Exhibitions.Status = 'End';
I guess it's not really a good design but I don't have another solution

Related

IBM db2 update substring in column

I have a table X with column Y (IBM db2) where column Y is a string of length less than 2048 characters. Some values in column Y contains string like ID some_value. I would like to remove all those keys and values. For example:
Row before update:
some text a ba ba b a ID sffjhdsf32484 further part etc etc
Row adter update:
some text a ba ba b a further part etc etc
how to achieve that?
I have following code up to now:
BEGIN
declare aaa anchor X.Y;
declare cur CURSOR for
SELECT Y
from X for update of Y;
open cur;
fetch cur into aaa;
update X.Y
set Y = //update logic
where current of cur;
close cur;
END;
unfortunatelly, It updates only first row in a table.
Does this help?
$ db2 "create table t(v varchar(2048))"
DB20000I The SQL command completed successfully.
$ db2 "insert into t values 'some text a ba ba b a ID sffjhdsf32484 further part etc etc'"
DB20000I The SQL command completed successfully.
$ db2 "update t set v = REGEXP_REPLACE(v,' ID sffjhdsf32484')"
DB20000I The SQL command completed successfully.
$ db2 "select v::varchar(60) from t"
1
------------------------------------------------------------
some text a ba ba b a further part etc etc
1 record(s) selected.
Use REGEXP_REPLACE function as in the following example:
SELECT REGEXP_REPLACE('String containing ID skskskk999s inside',
'ID\s.*\s', '',1,1,'c')
FROM sysibm.sysdummy1
Answer will be
1
------------------------
String containing inside
Knowing how REGEXP_REPLACE works, now you can use it in an UPDATE statement or any other statement you need. For example
UPDATE TBL SET SPECIFIC_COLUMN = REGEXP_REPLACE(
SPECIFIC_COLUMN,'ID\s.*\s', '',1,1,'c')

Postgres function with dblink

Got a problem here with following function in postgresql function:
im getting following error :
ERROR: query has no destination for result data
HINT: If you want to discard the results of a SELECT, use PERFORM instead.
CONTEXT: PL/pgSQL function savegamelog(text,text,integer,integer,bigint,bigint,bigint,integer,integer,integer,integer) line 15 at SQL statement
my function is as follows:
DECLARE
s text;
pDatatime integer;
pDataid bigint;
BEGIN
pDatatime = floor(extract(epoch from '["now()",]'::timestamp));
IF length(pTableName) > 0 THEN
UPDATE lastgamedata SET data= pData::bytea, gameid= pGameid, balance= pBalance ,bet= pBet, win= pWin, betline= pBetline, lines=pLines, datatime= pDatatime WHERE uid= pUserid;
END IF;
UPDATE gamestatistic SET totalin =totalin+pBet , totalout =totalout+pWin WHERE gameindex=pGameid;
SELECT dblink_connect('host=127.0.0.1
user=user
password=pass
dbname=dbname');
SELECT dblink_exec('UPDATE hall SET totalbetin = totalbetin+pBet , totalbetout =totalbetout+pWin WHERE id = (SELECT roomnumber FROM users WHERE uid = pUserid)');
INSERT INTO gamedata( sessionID, uid, gameID, key, balance, bet, win, betline, lines, datatime, type, denomination ) VALUES ( 0, pUserid, pGameid, 0, pBalance, pBet, pWin, pBetline, pLines, pDatatime, pType, pDenomination ) RETURNING dataid INTO pDataid;
INSERT INTO gamedata_storage ( dataid, data ) VALUES ( pDataid, pData::bytea );
return pDataid;
END;
i know the function is wrong, and i dont know how to fix it..
can anybody point me in the correct direction pls..
following the error message instructions, change
SELECT dblink_connect('host=127.0.0.1
user=user
password=pass
dbname=dbname');
to
PERFORM dblink_connect('host=127.0.0.1
user=user
password=pass
dbname=dbname');

Cannot insert NULL value into column error

I have a issue where I want to update a column in a table and with a trigger to update same column but in another table. It says I cannot insert NULL but I can't seem to understand from where it gets that NULL value. This is the trigger:
CREATE TRIGGER Custom_WF_Update_WF_DefinitionSteps_DefinitionId ON WF.Definition
AFTER UPDATE AS BEGIN
IF UPDATE(DefinitionId)
IF TRIGGER_NESTLEVEL() < 2
BEGIN
ALTER TABLE WF.DefinitionSteps NOCHECK CONSTRAINT ALL
UPDATE WF.DefinitionSteps
SET DefinitionId =
(SELECT i.DefinitionId
FROM inserted i,
deleted d
WHERE WF.DefinitionSteps.DefinitionId = d.DefinitionId
AND i.oldPkCol = d.DefinitionId)
WHERE WF.DefinitionSteps.DefinitionId IN
(SELECT DefinitionId FROM deleted)
ALTER TABLE WF.DefinitionSteps CHECK CONSTRAINT ALL
END
END
This update statement works just fine:
UPDATE [CCHMergeIntermediate].[WF].[Definition]
SET DefinitionId = source.DefinitionId + 445
FROM [CCHMergeIntermediate].[WF].[Definition] source
But this one fails:
UPDATE [CCHMergeIntermediate].[WF].[Definition]
SET DefinitionId = target.DefinitionId
FROM [CCHMergeIntermediate].[WF].[Definition] source
INNER JOIN [centralq3].[WF].[Definition] target
ON (((source.Name = target.Name) OR (source.Name IS NULL AND target.Name IS NULL)))
I get the following error:
Msg 515, Level 16, State 2, Procedure Custom_WF_Update_WF_DefinitionSteps_DefinitionId, Line 7
Cannot insert the value NULL into column 'DefinitionId', table 'CCHMergeIntermediate.WF.DefinitionSteps'; column does not allow nulls. UPDATE fails.
If I do a select instead of the update statement, like this:
SELECT source.DefinitionId, target.DefinitionId
FROM [CCHMergeIntermediate].[WF].[Definition] source
INNER JOIN [centralq3].[WF].[Definition] target
ON (((source.Name = target.Name) OR (source.Name IS NULL AND target.Name IS NULL)))
I get this result:
http://i.stack.imgur.com/3cZsM.png (sorry for external link, I don't have enaugh reputation to post image here )
What am I doing wrong? What I don't see? What am I missing..?
The problem was in the trigger at the condition. I modified the second where from i.oldPkCol = d.DefinitionId to i.oldPkCol = **d.oldPkCol** and it worked.
UPDATE WF.DefinitionSteps
SET DefinitionId =
(SELECT i.DefinitionId
FROM inserted i,
deleted d
WHERE WF.DefinitionSteps.DefinitionId = d.DefinitionId
AND i.oldPkCol = **d.oldPkCol**)
WHERE WF.DefinitionSteps.DefinitionId IN
(SELECT DefinitionId FROM deleted)

Inserting many rows in treelike structure in SQL SERVER 2005

I have a few tables in SQL that are pretty much like this
A B C
ID_A ID_B ID_C
Name Name Name
ID_A ID_B
As you can see, A is linked to B and B to C. Those are basically tables that contains data models. Now, I would need to be able to create date based on those tables. For example, if I have the following datas
A B C
1 Name1 1 SubName1 1 1 SubSubName1 1
2 Name2 2 SubName2 1 2 SubSubName2 1
3 SubName3 2 3 SubSubName3 2
4 SubSubName4 3
5 SubSubName5 3
I would like to copy the 'content' of those tables in others tables. Of course, the auto numeric key that is generated when inserting into the new tables are diffirent that those one and I would like to be able to keep track so that I can copy the entire thing. The structure of the recipient table contains more information that those, but it's mainly dates and other stuff that are easy to get for me.
I would need to this entirely in TRANSACT-SQL (with built-in function if needed). Is this possible and can anyone give me a short example. I manage to do it for one level, but I get confused for the rest.
thanks
EDIT : The info above is just an example, because my actual diagram looks more like this
Model tables :
Processes -- (1-N) Steps -- (1-N) Task -- (0-N) TaskCheckList
-- (0-N) StepsCheckLists
Where as the table I need to fill looks like this
Client -- (0-N) Sequence -- (1-N) ClientProcesses -- (1-N) ClientSteps -- (1-N)ClientTasks -- (0-N) ClientTaskCheckList
-- (0-N)ClientStepCheckLists
The Client already exists and when I need to run the script, I create one sequence, which will contains all processes, which will contains its steps, taks, etc...
Ok,
So I did a lot of trials and error, and here is what I got. It seems to work fine although it sound quite big for something that seemed easy at first.
The whole this is somehow in french and english because our client is french and so are we anyway. It does insert every date in all tables that I needed. The only thing left to this will be the first lines where I need to select the date to insert according to some parameters but this is the easy part.
DECLARE #IdProcessusRenouvellement bigint
DECLARE #NomProcessus nvarchar(255)
SELECT #IdProcessusRenouvellement = ID FROM T_Ref_Processus WHERE Nom LIKE 'EXP%'
SELECT #NomProcessus = Nom FROM T_Ref_Processus WHERE Nom LIKE 'EXP%'
DECLARE #InsertedSequence table(ID bigint)
DECLARE #Contrats table(ID bigint,IdClient bigint,NumeroContrat nvarchar(255))
INSERT INTO #Contrats SELECT ID,IdClient,NumeroContrat FROM T_ClientContrat
DECLARE #InsertedIdsSeq as Table(ID bigint)
-- Séquences de travail
INSERT INTO T_ClientContratSequenceTravail(IdClientContrat,Nom,DateDebut)
OUTPUT Inserted.ID INTO #InsertedIdsSeq
SELECT ID, #NomProcessus + ' - ' + CONVERT(VARCHAR(10), GETDATE(), 120) + ' : ' + NumeroContrat ,GETDATE()
FROM #Contrats
-- Processus
DECLARE #InsertedIdsPro as Table(ID bigint,IdProcessus bigint)
INSERT INTO T_ClientContratProcessus
(IdClientContratSequenceTravail,IdProcessus,Nom,DateDebut,DelaiRappel,DateRappel,LienAvecPro cessusRenouvellement,IdStatutProcessus,IdResponsable,Sequence)
OUTPUT Inserted.ID,Inserted.IdProcessus INTO #InsertedIdsPro
SELECT I.ID,P.ID,P.Nom,GETDATE(),P.DelaiRappel,GETDATE(),P.LienAvecProcessusRenouvellement,0,0,0
FROM #InsertedIdsSeq I, T_Ref_Processus P
WHERE P.ID = #IdProcessusRenouvellement
-- Étapes
DECLARE #InsertedIdsEt as table(ID bigint,IdProcessusEtape bigint)
INSERT INTO T_ClientContratProcessusEtape
(IdClientContratProcessus,IdProcessusEtape,Nom,DateDebut,DelaiRappel,DateRappel,NomListeVeri fication,Sequence,IdStatutEtape,IdResponsable,IdTypeResponsable,ListeVerificationTermine)
OUTPUT Inserted.ID,Inserted.IdProcessusEtape INTO #InsertedIdsEt
SELECT I.ID,E.ID,
E.Nom,GETDATE(),E.DelaiRappel,GETDATE(),COALESCE(L.Nom,''),E.Sequence,0,0,E.IdTypeResponsabl e,0
FROM #InsertedIdsPro I INNER JOIN T_Ref_ProcessusEtape E ON I.IdProcessus = E.IdProcessus
LEFT JOIN T_Ref_ListeVerification L ON E.IdListeVerification = L.ID
-- Étapes : Items de la liste de vérification
INSERT INTO T_ClientContratProcessusEtapeListeVerificationItem
(IdClientContratProcessusEtape,Nom,Requis,Verifie)
SELECT I.ID,IT.Nom,IT.Requis,0
FROM #InsertedIdsEt I
INNER JOIN T_Ref_ProcessusEtape E ON I.IdProcessusEtape = E.ID
INNER JOIN T_Ref_ListeVerificationItem IT ON E.IdListeVerification = IT.IdListeVerification
-- Tâches
DECLARE #InsertedIdsTa as table(ID bigint, IdProcessusEtapeTache bigint)
INSERT INTO T_ClientContratProcessusEtapeTache
(IdClientContratProcessusEtape,IdProcessusEtapeTache,Nom,DateDebut,DelaiRappel,DateRappel,No mListeVerification,Sequence,IdStatutTache,IdResponsable,IdTypeResponsable,ListeVerificationT ermine)
OUTPUT Inserted.ID,Inserted.IdProcessusEtapeTache INTO #InsertedIdsTa
SELECT I.ID,T.ID,
T.Nom,GETDATE(),T.DelaiRappel,GETDATE(),COALESCE(L.Nom,''),T.Sequence,0,0,T.IdTypeResponsabl e,0
FROM #InsertedIdsEt I
INNER JOIN T_Ref_ProcessusEtapeTache T ON I.IdProcessusEtape = T.IdProcessusEtape
LEFT JOIN T_Ref_ListeVerification L ON T.IdListeVerification = L.ID
-- Tâches : Items de la liste de vérification
INSERT INTO T_ClientContratProcessusEtapeTacheListeVerificationItem
(IdClientContratProcessusEtapeTache,Nom,Requis,Verifie)
SELECT I.ID,IT.Nom,IT.Requis,0
FROM #InsertedIdsTa I
INNER JOIN T_Ref_ProcessusEtapeTache T ON I.IdProcessusEtapeTache = T.ID
INNER JOIN T_Ref_ListeVerificationItem IT ON T.IdListeVerification = IT.IdListeVerification

Nested SELECT statement in a CASE expression

Greetings,
Here is my problem.
I need to get data from multiple rows and return them as a single result in a larger query.
I already posted a similar question here.
Return multiple values in one column within a main query but I suspect my lack of SQL knowledge made the question too vague because the answers did not work.
I am using Microsoft SQL 2005.
Here is what I have.
Multiple tables with CaseID as the PK, CaseID is unique.
One table (tblKIN) with CaseID and ItemNum(AutoInc) as the combined PK.
Because each person in the database will likely have more than one relative.
If I run the following, in a SQL query window, it works.
DECLARE #KINList varchar(1000)
SELECT #KINList = coalesce(#KINList + ', ','') + KINRel from tblKIN
WHERE CaseID = 'xxx' and Address = 'yyy'
ORDER BY KINRel
SELECT #KINList
This will return the relation of all people who live at the same address. the results look like this...
Father, Niece, Sister, Son
Now, the problem for me is how do I add that to my main query?
Shortened to relevant information, the main query looks like this.
SELECT DISTINCT
c.CaseID,
c.Name,
c.Address,
Relatives=CASE WHEN exists(select k.CaseID from tblKIN k where c.CaseID = k.CaseID)
THEN DECLARE #KINList varchar(1000)
SELECT #KINList = coalesce(#KINList + ', ','') + KINRel from tblKIN
WHERE CaseID = 'xxx' and Address = 'yyy'
ORDER BY KINRel
SELECT #KINList
ELSE ''
END
FROM tblCase c
ORDER BY c.CaseID
The errors I receive are.
Server: Msg 156, Level 15, State 1, Line 13
Incorrect syntax near the keyword 'DECLARE'.
Server: Msg 156, Level 15, State 1, Line 18
Incorrect syntax near the keyword 'ELSE'.
I tried nesting inside parenthesis from the DECLARE to the end of the SELECT #KINList.
I tried adding a BEGIN and END to the THEN section of the CASE statement.
Neither worked.
The source table data looks something like this. (periods added for readability)
tblCase
CaseID Name Address
10-001 Jim......100 Main St.
10-002 Tom....150 Elm St.
10-003 Abe.....200 1st St.
tblKIN
CaseID ItemNum Name Relation Address
10-001 00001 Steve...Son........100 Main St.
10-002 00002 James..Father....150 Elm St.
10-002 00003 Betty....Niece......150 Elm St.
10-002 00004 Greta...Sister.....150 Elm St.
10-002 00005 Davey..Son........150 Elm St.
10-003 00006 Edgar...Brother...200 1st St.
If I run the query for CaseID = 10-002, it needs to return the following.
CaseID Name Address.......Relatives
10-002 Tom...150 Elm St. ..Father, Niece, Sister, Son
I am sure this is probably a simple fix, but I just don't know how to do it.
Thank you for your time, and I apologize for the length of the question, but I wanted to be clear.
Thanks !!!
When I did something similar I had to create a scalar function to do the coalesce that returns the varchar result. Then just call it in the select.
CREATE FUNCTION GetRelatives
(
#CaseID varchar(10)
)
RETURNS varchar(1000)
AS
BEGIN
DECLARE #KINList varchar(1000)
SELECT #KINList = coalesce(#KINList + ', ','') + KINRel from tblKIN
WHERE CaseID = #CaseID
ORDER BY KINRel
RETURN #KINList
END
Then your select
SELECT DISTINCT
c.CaseID,
c.Name,
c.Address,
database.dbo.GetRelatives(c.CaseID) AS Relatives
FROM tblCase c
ORDER BY c.CaseID
You can create a FUNCTION which takes in the caseID as the arguement and returns true or false.
Since you are calling the nested query multiple times, its definitely a performance hit. A better solution is to execute the query and store the results in a temporary table.
Then pass this temporary table and the caseID to the FUNCTION and check for containment.