I need to make sure that I did my coding right for these problem okay - sqlplus

These are the question to the problem
Set echo on
2. SET SERVEROUT ON
3. Set up a spool file to receive your output for submission. I would suggest c:\CS4210\wa5spool.txt .
4. DECLARE a record variable (Emp_rec) using %ROWTYPE
5. In the BEGIN block add a select statement to read a record into the declared variable from HR.EMPLOYEES
6. Add If Statement to print record
7. Add DBMS_OUTPUT lines to print EMPLOYEE_ID, FIRST_NAME, LAST_NAME, and SALARY for the selected record
8. Use TO_CHAR to format the salary as $999,999
9. Add a EXCEPTION block to report when no data is found
10. Compile and run the procedure.
11. Close the spool file
CLARIFICATION: For this assignment, you can use your IF statement to do whatever you want. You can use it to determine the Department, like we did in the past with a CASE, or you can do it to print a message if they make over a certain amount of money, or maybe they are due a raise if they were hired before a certain date. Use your imagination.
:
set echo on
set SERVEROUTPUT ON
DECLARE
Emp_rec employee%rowtype;
BEGIN
SELECT * into emp_rec FROM HR.EMPLOYEES WHERE EMPLOYEE_ID = 5;
IF Emp_rec.EMPLOYEE_ID = 5 THEN
dbms_output.put_line('Employee ID : ' || Emp_rec.EMPLOYEE_ID);
dbms_output.put_line('First Name : ' || Emp_rec.FIRST_NAME);
dbms_output.put_line('Last Name : ' || Emp_rec.LAST_NAME);
dbms_output.put_line('Salary: ' || TO_CHAR(Emp_rec.salary,'$99,990.99'));
END IF;
EXCEPTION
WHEN NO_DATA_FOUND THEN
INSERT INTO errors VALUES ('No record found in the table ' );
END;
spool off

As your table seems to be HR.EMPLOYEES, your declaration of a rowtype should be HR.EMPLOYEES%rowtype.

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.

Teradata : Stored Procedure : parameter column name

I'm looking for help with a stored procedure in teradata. I want to update a whole table and for this I'm trying to use a for loop cursor. the problem is that my update is defined via column names passing through parameters to the SP.
I've seen it can be possible to use dynamic sql to do that but I haven't found any information on the subject concerning for loop cursor and dynamic sql. Is it possible with FOR LOOP CURSOR ?
I've tried to do only the select and calculs with dynamic sql, it works fine but then the problem is to update the table from the cursor on the select. In this case how to update a table from my cursor?
I let you show my code.
loop cursor :
REPLACE PROCEDURE [database].calDELAI
(
IN dateDebut VARCHAR(30),
IN dateFin VARCHAR(30),
IN delay VARCHAR(30)
)
BEGIN
DECLARE DATE_DEBUT_COLONNE VARCHAR(64);
DECLARE DATE_FIN_COLONNE VARCHAR(64);
SET DATE_DEBUT_COLONNE=dateDebut;
SET DATE_FIN_COLONNE=dateFin;
FOR for_loop_update AS cur_select_set CURSOR FOR
SELECT
TMP.DATE_FIN_COLONNE-TMP.DATE_DEBUT_COLONNE
FROM [database].ORD_T_DETL_ORDR_DELAI AS TMP
/* the select is more complicated but here is the spirit of it.*/
DO
IF (delay='DELAI1') THEN SET DELAI1=NB_JR_OUVRABLE;
END IF;
END FOR ;
END ;
The errors given by teradata are :
SPL1027:E, Missing/Invalid SQL statement'E(3810):Column/Parameter '[database].TMP.DATE_FIN_COLONNE' does not exist.'.
SPL2001:E, Undefined symbol 'DELAI1'.
SPL2001:E, Undefined symbol 'NB_JR_OUVRABLE'.
Thanks in advance for your replies and your help.
The call statement should contain all the input Paramenters , make sure you are specifying all the input parameters correctly. Could you please provide your call statement.

Calling Oracle 11g Stored Procedure Using VB6

I have a simple Oracle procedure as below. I am trying to call the procedure using VB6 and extract the output from the procedure.
CREATE OR REPLACE PROCEDURE EXTRACTTXN (reportdate IN DATE, p_recordset OUT SYS_REFCURSOR) AS
BEGIN
OPEN p_recordset FOR
SELECT
TXN_ID,
TXN_ACTION,
TXN_STATUS,
TXN_DATE,
TXN_AMOUNT
FROM TRANSACTIONS
WHERE
TRUNC(TXN_DATE) = TRUNC(reportdate)
END EXTRACTTXN;
The VB Code goes like this;
Sub FetchTransactions(ByVal ReportDate As Date, cnnMine as ADODB.Connection)
On Error GoTo TrapErr
Dim cmdMine As ADODB.Command, rsMine As ADODB.Recordset
cmdMine.ActiveConnection = cnnMine
cmdMine.CommandTimeout = 300
cmdMine.CommandType = adCmdStoredProc
cmdMine.CommandText = "EXTRACTTXN"
cmdMine.Parameters.Append cmdMine.CreateParameter("reportdate", adDate, adParamInput, , Format(ReportDate, "DD-MMM-YYYY"))
cmdMine.Parameters.Append cmdMine.CreateParameter("p_recordset", adVariant, adParamOutput)
Set rsMine = cmdMine.Execute
Do While rsMine.EOF
Debug.Print rsMine!TXN_ID, rsMine!TXN_ACTION, rsMine!TXN_STATUS, rsMine!TXN_DATE, rsMine!TXN_AMOUNT
rsMine.MoveNext
Loop
rsMine.Close
Exit Sub
TrapErr:
MsgBox Err.Number & " - " & Err.Description, vbExclamation, App.ProductName
End Sub
While running the code, I get the following Error:
ORA-06550: line 1, column 7:
PLS-00306: wrong number or types of arguments in call to 'EXTRACTTXN'
ORA-06550: line 1, column 7:
PL/SQL: Statement ignored
Anything wrong in my code? Appreciate help.
Niz
The problem is that the types of your arguments as specified in your VB code don't match the types of the arguments as specified in your PL/SQL code. The most likely reason for your problem is that the Format function in VB6 returns a Variant type, not a Date type, and that Variant type is set to be a String type. See this for more information on the Format function.
In case you don't know, the way that Variant variables are set up is that they reserve 8 bytes to tell the world what the actual variable type is. So, if you pass your ReportDate in after applying the Format function to it, it will be a Variant that's telling the world it's a string. It's possible that the ADO Parameter object is happy with that (SQL Server is happy to parse properly-formatted strings into Date fields, after all) and Oracle isn't. In my limited experience with Oracle, I've found that it's fussier about that sort of thing than SQL Server.
Try losing the Format function and see if you at least get a different error.
I have managed to get this sorted. It's mainly due to me being new to Oracle and its complexity.
Here are the changes I made;
Stored Procedure Changes. Note that I have changed TRUNC(reportdate, 'DD') on the Where clause.
CREATE OR REPLACE PROCEDURE EXTRACTTXN (reportdate IN DATE, p_recordset OUT SYS_REFCURSOR) AS
BEGIN
OPEN p_recordset FOR
SELECT
TXN_ID,
TXN_ACTION,
TXN_STATUS,
TXN_DATE,
TXN_AMOUNT
FROM TRANSACTIONS
WHERE
TRUNC(TXN_DATE) = TRUNC(reportdate, 'DD')
END EXTRACTTXN;
VB Code Changes (Note that I have change the CommandText within parenthesis with a Call, removed the parameter name, changed the date format to DD/MMM/YYYY and removed the output parameter)
Sub FetchTransactions(ByVal ReportDate As Date, cnnMine as ADODB.Connection)
On Error GoTo TrapErr
Dim cmdMine As ADODB.Command, rsMine As ADODB.Recordset
cmdMine.ActiveConnection = cnnMine
cmdMine.CommandTimeout = 300
cmdMine.CommandType = adCmdStoredProc
cmdMine.CommandText = "{ call EXTRACTTXN}"
cmdMine.Parameters.Append cmdMine.CreateParameter(, adDate, adParamInput, , Format(ReportDate, "DD/MMM/YYYY"))
Set rsMine = cmdMine.Execute
Do While rsMine.EOF
Debug.Print rsMine!TXN_ID, rsMine!TXN_ACTION, rsMine!TXN_STATUS, rsMine!TXN_DATE, rsMine!TXN_AMOUNT
rsMine.MoveNext
Loop
rsMine.Close
Exit Sub
TrapErr:
MsgBox Err.Number & " - " & Err.Description, vbExclamation, App.ProductName
End Sub
The above worked perfectly.
Regards, Niz

How can I call a DB2 stored procedure with OUT parameters from SQuirreL SQL?

I really like SQuirreL SQL as a SQL query tool, but I've never been able to get it to call stored procedures in our AS/400 DB2 database. I always get the error "The number of parameter values set or registered does not match the number of parameters." I've double-checked the number of params and had no luck. This is the syntax I've tried for a procedure that takes one IN and one OUT:
call SOMESPROC(12345, ?);
It seems that SQuirrel currently is not capable of doing that on AS/400 DB2.
Using the open source "SQL Workbench/J" (http://www.sql-workbench.net/) I was able to call a procedure:
wbcall SOMESPROC(12345, ?);
It has its own command for calling a procedure "wbcall". Use ? for out parameters.
Note: While installing SQL Workbench/J make sure to download the right DB2 driver from IBM and also add the licence file while adding the driver inside SQL Workbench/J.
In Squirrel you can use something like this. You'll want to make sure the type of the declared variable matches the type of your out parameter in the stored procedure.
BEGIN
DECLARE outParam INT;
STORED_PROC_NAME(outParam);
END
If you also need to provide input for the procedure you could do this.
BEGIN
DECLARE outParam INT;
STORED_PROC_NAME('input', outParam);
END
You also need to change the statement separator to something other than ;. Otherwise it will break up the statement and try to send each piece individually.
In the pro version of DbVisualizer, with the "Process Parameter Markers in SQL" under the SQL Commander menu option enabled, it will allow the "?" param
call SOMESPROC(12345, ?);
through trial and error, I was able to see the results in Squirrel.
create or replace variable var4 char(1);
create or replace variable var5 decimal(3,0);
create or replace variable var6 char(60);
call getthedata('XXX',123456789,'1234567',var4,var5,var6);
select var4,var5,var6 from sysibm.sysdummy1; -- displays OUT parms
I would think that if there is one in then the call should be:
CALL SomeSProc(12345)
to get a result maybe try:
SELECT * FROM SomeSProc(12345)
Here is an tested example which works on Squirrel 3.7 with a db2 stored procedure . The trick is to passe with an transitional stored procedure MY_PROC_TEST to call the real stored procedure PROC_TEST.
change statement separator in squirrel > session > session properties > SQL : #
DROP PROCEDURE MY_PROC_TEST()#
CREATE PROCEDURE MY_PROC_TEST()
RESULT SETS 1 -- out resultset (call product)
LANGUAGE SQL
BEGIN
DECLARE flag SMALLINT; -- out parameter
CALL MY_PROC('2015', flag);
END #
CALL MY_PROC_TEST()#
END #
Then you can call the sored procedure like this :
CALL MY_PROC_TEST()#
This will work in Squirrel if you change the delimiter (as specified above). However, to see what the variable is, you need to do the following...
In my example, I will set the delimiter to a tildy (~). Include after last "end", before "select". Code begins here...
begin
declare inoutParm numeric(2,0);
call spMyStoredProcedure(
1234567
, inoutParm
);
declare global temporary table session.myTempTbl
(MyResult char(1024) )
with replace ;
insert into session.myTempTbl
(myResult)
values(inoutParm) ;
end
~
select myResult from session.myTempTbl
Mic Keeley
as400(db2) SQL Developer
I was able to cobble together some amalgamation of all of the above answers and came up with this which worked for me. I'm using Squirrel SQL 2018 connecting to an IBM AS/400 DB2 database. I did have to declare a statement separator, I used "#".
BEGIN
DECLARE success CHAR(1); -- output parameters
DECLARE message CHAR(300);
SET success = ' ';
SET message = ' ';
CALL myProc('some', 'params', 4, success, message);
DECLARE GLOBAL TEMPORARY TABLE session.myTmp(s_res CHAR(1), m_res CHAR(300)) WITH REPLACE;
INSERT INTO session.myTmp(s_res, m_res) VALUES(success, message);
END
# -- <- statement separator needs to be set to something other than ";" in this case it's set to "#"
SELECT * FROM session.myTmp;
change statement separator in squirrel > session > session properties > SQL : '#'
BEGIN
DECLARE inOutParam varchar(200);
set inOutParam = 'a value';
STORED_PROC_NAME(outParam);
END;
#

Resources