T-SQL Error in non-executing branch of if..else block - stored-procedures

I'm hitting my head against the wall with this one.
We have a stored procedure that is being called in an API that we are developing and the stored procedure has the following code:
if(#StatusCode = 41 and #OperationName != 'convert')
Begin
EXEC [uspCreateOrg] #RequestID = #_RequestId
End
else
Begin
EXEC [uspUpsertOrg] #RequestID = #_RequestId
End
Using the profiler, we can that the 'if' branch is the one that gets executed, but we also see that SQL Server is looking down the 'else' branch and calling into that stored procedure and throwing an exception. The uspUpsertOrg procedure calls the DBAmp BulkOps which has the following code in it:
create table #errorlog (line varchar(255))
insert into #errorlog
exec #Result = master..xp_cmdshell #Command
-- print output to msgs
declare #line varchar(255)
declare #printCount int
set #printCount = 0
DECLARE tables_cursor CURSOR FOR SELECT line FROM #errorlog
OPEN tables_cursor
FETCH NEXT FROM tables_cursor INTO #line
WHILE (##FETCH_STATUS <> -1)
BEGIN
if #line is not null
begin
print #line
exec SF_Logger #SPName,N'Message', #Line
set #errorLines = #errorLines + #line
set #printCount = #printCount +1
end
FETCH NEXT FROM tables_cursor INTO #line
END
deallocate tables_cursor
-- drop temp output table
drop table #errorlog
The exception that gets thrown is that the #errorLog table does not exist. So in summary we are getting an exception that a temp table created on the line above the insert does not exist in a stored procedure that does not even get called...Fun...
When we comment out the call to uspUpsertOrg everything works as expected. When we change the temp table to a real table, it still fails, but if we create it outside the procedure and then run the process, it works. In any of these cases, the code does not go down the 'else' branch in the sense that the 'else' branch would be the one that gets executed. It's almost as if SQL server is looking ahead down all code paths--I know that SQL Server does that kind of thing for optimization, etc, but why would it miss the fact that the table IS being created before use? I've done this kind of thing before and never had problems.
Thanks for the help!

According to this article on Execution Plan Basics, this exact scenario causes a problem for the algebrizer that doesn't execute your code, but is responsible for generating the execution plan. Look for the section When the Estimated Plan is Invalid.
I think this workaround will work for you: Instead of the CREATE statement, use
SELECT CAST('' as VARCHAR(255)) as line INTO #errorlog

Related

Inserting name into database, getting korean signs as output

Trying to insert simple xml file with one row in IIB with simple message flow into Oracle XE DB. Message flow works fine and inserts data into database, but data written in db is different from starting data. For example, as I'm trying to insert my name "Dino" I'd get Korean/Japanese/Chinese signs in return.
I've tried changing XML formats thinking there might be problem, but I suppose it has to do with encoding.
Input:
Output in DB:
This is how my compute node looks like:
CREATE COMPUTE MODULE SimpleDB_mf_Compute
CREATE FUNCTION Main() RETURNS BOOLEAN
BEGIN
CALL CopyMessageHeaders();
-- CALL CopyEntireMessage();
INSERT INTO Database.dkralj.emp VALUES(InputRoot.XMLNSC.emp.name);
SET OutputRoot.XMLNSC.DBINSERT.STATUS='SUCCESS';
RETURN TRUE;
END;
CREATE PROCEDURE CopyMessageHeaders() BEGIN
DECLARE I INTEGER 1;
DECLARE J INTEGER;
SET J = CARDINALITY(InputRoot.*[]);
WHILE I < J DO
SET OutputRoot.*[I] = InputRoot.*[I];
SET I = I + 1;
END WHILE;
END;
CREATE PROCEDURE CopyEntireMessage() BEGIN
SET OutputRoot = InputRoot;
END;
END MODULE;
Looking at the IBM documentation for the INSERT statement in ESQL it might be worth trying.
INSERT INTO Database.dkralj(NAME) VALUES(InputRoot.XMLNSC.emp.name);
If weird things are still happening then I'd try a string constant to avoid any issues with character coding in the input message.
INSERT INTO Database.dkralj(NAME) VALUES('TheEmpValue');
Before this statement in your code
SET OutputRoot.XMLNSC.DBINSERT.STATUS='SUCCESS';
You should check for success or otherwise by using the inbuilt SQLSTATE, SQLCODE, SQLERRORTEXT to check the result of your call.
IF NOT ((SQLCODE = 0) OR (SQLSTATE = '01000' AND SQLNATIVEERROR = 8153)) THEN
-- Do something about the error.
-- The check of SQLSTATE and SQLNATIVEERROR covers warnings
-- The 8153 is for Microsoft SQL Server other databases may use a different value
END IF;
Also check the codepages aka CodedCharSetId of the source system data, the message in IIB and the default codepage of the database.
Use mqsicvp MYBROKER -n ODBC_DB_NAME to get other details about the connection you need to use -n to get the details.
Use something like DBeaver to add some data. Have a look at the datatype specified for the field.
As per your comment below and my response here is an example of a PASSTHRU statement. Note the use of the ? to avoid SQL Injection.
PASSTHRU('SELECT RTRIM(A.EMPLID) AS EMPLID,
RTRIM(A.ADDRESS_TYPE) AS ADDRESS_TYPE,
RTRIM(A.ADDR_TYPE_DESCR) AS ADDR_TYPE_DESCR,
CAST(RTRIM(A.EFFDT) AS DATE) AS EFFDT,
RTRIM(A.EFF_STATUS) AS EFF_STATUS,
RTRIM(A.ADDRESS1) AS ADDRESS1,
RTRIM(A.ADDRESS2) AS ADDRESS2,
RTRIM(A.ADDRESS3) AS ADDRESS3,
RTRIM(A.ADDRESS4) AS ADDRESS4,
RTRIM(A.CITY) AS CITY,
RTRIM(A.STATE) AS STATE,
RTRIM(A.POSTAL) AS POSTAL
FROM ADDRESS_VW AS A
WHERE UPPER(A.EMPLID) = ?') VALUES(AggrRef.EmployeeID)

Clean MySQL tables with failed foreign checks

I have a giant mysql sql dump file. But I'm getting error when I try to import it because of foreign key checks. Somehow there is missing data, so I'm importing it with
SET SESSION FOREIGN_KEY_CHECKS=0;
and it works, but I'm looking for a solution for missing data.
So is there any automatic way to find and delete relation data with missing entries to get a clean database dump, or I have to go and write manuel SQL for every relation, write query to delete missing values ?
You can automate a delete statement like this:
DELIMITER $$
DROP PROCEDURE IF EXISTS check_foreign $$
CREATE DEFINER=`root`#`localhost` PROCEDURE `check_foreign`()
BEGIN
DECLARE finishing INTEGER DEFAULT 0;
DECLARE vstmt VARCHAR(4000);
DECLARE vtbname VARCHAR(50);
DECLARE vtbnameref VARCHAR(50);
DECLARE vtbcol VARCHAR(50);
DECLARE vtbcolref VARCHAR(50);
DECLARE cr_tables CURSOR FOR select a.table_name, a.referenced_table_name, a.column_name, a.referenced_column_name from information_schema.KEY_COLUMN_USAGE a where a.table_schema = 'protocol_manager' and a.REFERENCED_TABLE_NAME is not null order by a.table_name;
DECLARE CONTINUE HANDLER FOR not found SET finishing = 1;
OPEN cr_tables;
SET vstmt = '';
table_foreign_delete: loop
if finishing = 1 then
leave table_foreign_delete;
end if;
FETCH cr_tables INTO vtbname, vtbnameref, vtbcol, vtbcolref;
SET vstmt = CONCAT(vstmt, char(10), 'DELETE FROM ', vtbname, ' a WHERE NOT EXISTS (SELECT 1 FROM ', vtbnameref, ' b WHERE a.', vtbcol, ' = b.', vtbcolref, ');');
end loop table_foreign_delete;
select vstmt;
END$$
DELIMITER ;
You can even do deep search to find a way to execute it dynamicly. For example a temporary table with a trigger. You generate a delete statement, insert it into the temp table, trigger the insert that fires a another (func, proc) to execute the statement generated.

How can I deploy a DB2 stored procedure which writes to a table that does not yet exist (but will by the time it does so)?

As you would most likely have deduced from the following question, I am new to DB2 in general. I am attempting to write my second ever stored procedure using IBM Data Studio and am running into an error when trying to deploy it. The point of the stored procedure is to search for a text string in fields across different tables. NOTE: The code is not complete and is not useful in its current form. I am attempting to test each step as I go along.
Here is all of the code I have so far:
CREATE OR REPLACE PROCEDURE sp_find_string (in in_search_string varchar(200), in in_schema varchar(50))
DYNAMIC RESULT SETS 1
P1: BEGIN
-- #######################################################################
-- #
-- #######################################################################
declare table_a varchar(200);
declare colname varchar(200);
declare sqlcmd varchar(2000);
declare eof smallint default 0;
declare not_found condition for sqlstate '02000';
-- Declare cursor
DECLARE cursor1 CURSOR WITH RETURN for
select tabname, colname from syscat.columns c
--inner join syscat.tables t on t.tabschema = c.tabschema
-- and t.tabname = c.tabname
where tabname like 'MERLIN%'
and tabschema = in_schema;
DECLARE CONTINUE HANDLER FOR SQLSTATE '42704' -- or SQLEXCEPTION
-------------------------------------------------
if (exists
(
select 1 from sysibm.systables
where creator = 'A2815'
and name = 'DBP_TEMP_SEARCH_RESULTS'
)
) then drop table A2815.DBP_TEMP_SEARCH_RESULTS;
end if;
create table A2815.DBP_TEMP_SEARCH_RESULTS
(text_to_match varchar(200)
,table_a varchar(200)
,colname varchar(200)
,match_count bigint);
-- Cursor left open for client application
OPEN cursor1;
while eof = 0 do
p2: begin
declare continue handler for not_found set eof = 1;
fetch from cursor1 into table_a, colname;
insert into A2815.DPB_TEMP_SEARCH_RESULTS
values(table_a, colname);
end p2;
end while;
close cursor1;
--return;
END P1
I am getting this error when attempting to deploy:
Deploy [TIO_D]A2815.SP_FIND_STRING(VARCHAR(200), VARCHAR(50))
Running
A2815.SP_FIND_STRING - Deploy started.
Create stored procedure returns SQLCODE: -204, SQLSTATE: 42704.
A2815.SP_FIND_STRING: 44: "A2815.DPB_TEMP_SEARCH_RESULTS" is an undefined name.. SQLCODE=-204, SQLSTATE=42704, DRIVER=4.18.60
"A2815.DPB_TEMP_SEARCH_RESULTS" is an undefined name.. SQLCODE=-204, SQLSTATE=42704, DRIVER=4.18.60
A2815.SP_FIND_STRING - Deploy failed.
A2815.SP_FIND_STRING - Roll back completed successfully.
When I comment out the insert statement, it deploys just fine (but of course the procedure doesn't do me much good without the ability to insert):
OPEN cursor1;
while eof = 0 do
p2: begin
declare continue handler for not_found set eof = 1;
fetch from cursor1 into table_a, colname;
--insert into A2815.DPB_TEMP_SEARCH_RESULTS
--values(table_a, colname);
end p2;
end while;
close cursor1;
It is true that the table does not exist yet, because it should be created by the procedure. However, if I create the table then deploy the procedure I get this error:
Deploy [TIO_D]A2815.SP_FIND_STRING(VARCHAR(200), VARCHAR(50))
Running
A2815.SP_FIND_STRING - Deploy started.
Create stored procedure returns SQLCODE: -601, SQLSTATE: 42710.
A2815.SP_FIND_STRING: 32: The name of the object to be created is identical to the existing name "A2815.DBP_TEMP_SEARCH_RESULTS" of type "TABLE".. SQLCODE=-601, SQLSTATE=42710, DRIVER=4.18.60
The name of the object to be created is identical to the existing name "A2815.DBP_TEMP_SEARCH_RESULTS" of type "TABLE".. SQLCODE=-601, SQLSTATE=42710, DRIVER=4.18.60
A2815.SP_FIND_STRING - Deploy failed.
A2815.SP_FIND_STRING - Roll back completed successfully.
Can anyone tell me how to get this procedure deployed either when the table exists, when it doesn't exist, or both?
Thank you very much and let me know what other detail is needed. Also, suggestions on how to improve the code in general would be great as well.
The simplest solution is simply to create that table so that it exists before you compile the procedure. If you just run the create table statement manually before compiling the procedure, then there will be no problem.
Commenters have suggested that you should use Declare Global Temporary Table, and I agree with this, since you appear to be using this as a temporary table. However, it doesn't actually solve your specific problem, since the procedure still won't compile if the temporary table doesn't exist at compile time. So, yes, use a temporary table, but you will still have to do the same thing.
Changing the insert statement to dynamic SQL would also work, though it is an ugly solution. Not necessary here, but sometimes it is needed.
Might be a bit late, but the best way to do this would be to create a string with your query, instead of using the query directly, and then using EXECUTE IMMEDIATELY

BEFORE INSERT trigger with stored procedure call (DB2 LUW 9.5)

I am trying to create a BEFORE INSERT trigger that will check the incoming value of a field, and replace it with the same field in another row if that the field is null. However, when I add the CALL statement to my trigger, an error is returned "The trigger "ORGSTRUCT.CSTCNTR_IN" is defined with an unsupported triggered SQL statement". I checked the documentation and saw that cursors weren't supported in the BEFORE (part of the reason for making the stored procedure in the first place), but even when I remove the cursor declaration from the stored procedure the call still generates the same error.
Trigger:
CREATE TRIGGER orgstruct.cstcntr_IN
NO CASCADE
BEFORE INSERT ON orgstruct.tOrgs
REFERENCING NEW AS r
FOR EACH ROW MODE DB2SQL
BEGIN ATOMIC
DECLARE prnt_temp BIGINT;
DECLARE cstcntr_temp CHAR(11);
SET prnt_temp = r.prnt;
SET cstcntr_temp = r.cstcntr;
CALL orgstruct.trspGetPrntCstCntr(prnt_temp,cstcntr_temp);
SET r.cstcntr = cstcntr_temp;
END
Stored procedure:
CREATE PROCEDURE orgstruct.trspGetPrntCstCntr (
IN p_prnt BIGINT,
OUT p_cstcntr CHAR(11)
)
SPECIFIC trGetPrntCstCntr
BEGIN
IF p_prnt IS NULL THEN
RETURN;
END IF;
BEGIN
DECLARE c1 CURSOR
FOR
SELECT cstcntr
FROM orgstruct.tOrgs
WHERE id = p_prnt
FOR READ ONLY;
OPEN c1;
FETCH FROM c1 INTO p_cstcntr;
CLOSE c1;
END;
END
According to the documentation, CALL is allowed in a BEFORE trigger, so I don't understand what the problem is.
A before trigger can call a stored procedure, but the stored proc can't do anything not allowed in the trigger.
In your case, the default level of data access for a SQL stored proc is MODIFIES SQL DATA, which is not allowed in the trigger. You could recreate your stored procedure, changing the data access level to READS SQL DATA; this will allow you to create the trigger.
However: There is no reason to call a stored procedure for something this simple; You can do it using a simple inline trigger:
create trigger orgstruct.cstcntr_IN
no cascade
before insert on orgstruct.tOrgs
referencing new as r
for each row
mode db2sql
set r.cstcntr = case
when r.p_prnt is not null
then (select cstcntr from tOrgs where id = r.p_prnt fetch first 1 row only)
else r.cstcntr
end;
This will be a LOT more efficient because it eliminates both the stored procedure call and the cursor processing inside the stored proc. Even if you wanted to use the stored proc, you could eliminate the cursor inside the stored proc and improve performance.
FYI: the logic that you posted contains an error, and will always set CSTCNTR to NULL. The trigger posted in this answer not do this. :-)

Error -104 creating Firebird stored procedure

I cannot run the following SP
CREATE PROCEDURE SP_NYANSAT(
FORNAVN VARCHAR(30),
EFTERNAVN VARCHAR(30),
ADRESSE VARCHAR(50),
POSTNUMMER CHAR(4),
TELEFONNUMMER CHAR(8),
EMAIL VARCHAR(50))
AS
DECLARE VARIABLE ID INTEGER;
BEGIN
ID = GEN_ID(GEN_ANSAT_ID,1);
INSERT INTO MYTABLE (ID, FORNAVN, EFTERNAVN, ADRESSE, POSTNUMMER, TELEFONNUMMER, EMAIL) VALUES (:ID, :FORNAVN, :EFTERNAVN, :ADRESSE, :POSTNUMMER, :TELEFONNUMMER, :EMAIL);
END
The error I get is the following:
can't format message 13:896 -- message file C:\Windows\firebird.msg not found.
Dynamic SQL Error.
SQL error code = -104.
Token unknown - line 3, column 1.
CREATE.
Have you used Set Term before and after this code?
All commands in Firebird must be terminated with a semi-colon. If you want to create a stored procedure you need to be able to distinguish between the terminating semi-colon from the semi-colons inside the stored procedure.
Something like this:
SET TERM ^ ;
CREATE PROCEDURE SP_NYANSAT(
FORNAVN VARCHAR(30),
EFTERNAVN VARCHAR(30),
ADRESSE VARCHAR(50),
POSTNUMMER CHAR(4),
TELEFONNUMMER CHAR(8),
EMAIL VARCHAR(50))
AS
DECLARE VARIABLE ID INTEGER;
BEGIN
ID = GEN_ID(GEN_ANSAT_ID,1);
INSERT INTO MYTABLE (ID, FORNAVN, EFTERNAVN, ADRESSE, POSTNUMMER, TELEFONNUMMER, EMAIL) VALUES (:ID, :FORNAVN, :EFTERNAVN, :ADRESSE, :POSTNUMMER, :TELEFONNUMMER, :EMAIL);
END
^
SET TERM ; ^
Please notice how the declaration of the stored procedure is terminated with ^, thus ending the statement. After the declaration you also restore the terminating semi-colon.
On a side note, I would recommend to copy firebird.msg to the location the error you get tells you so you can see what is really happening.
EDIT:
If you wish you can check this link. There you can find a lot of information regarding Firebird + IBExpress, including SET TERM (page 81).
EDIT 2:
Just tried at home with IBExperts + Firebird and I had no problem creating the stored procedure. My guess is you are trying to do one of the following things:
You have opened an SQL editor and are trying to compile the code directly. That will not work because IBExperts thinks you are trying to run DSQL sentences. Stored procedures are created with PSQL sentences.
You are trying to use the "New procedure" utility (check buttons in the upper right side of the main menu) and pasted the whole code into the editor. That will not work because in that editor you only have to put the body code. Stored procedure name is set in a field on the upper right side of the window you opened. Parameters and variables are introduced by using the "Insert Parameter/Variable" button on the left side above the code editor. The SET TERM sentences are created automatically by IBExperts. You can check the resulting code in the DDL tab.
HTH

Resources