Discover DB2 procedure default parameters using SYSCAT tables - sql

Like Oracle, DB2 supports parameter defaults in stored procedures. Oracle syntax:
CREATE OR REPLACE PROCEDURE p_default (
p_in_number IN number := 0,
p_out_number OUT number,
p_in_varchar IN varchar2 := '0',
p_out_varchar OUT varchar2,
p_in_date IN date := date '1981-07-10',
p_out_date OUT date
)
DB2 syntax:
CREATE PROCEDURE p_default (
IN p_in_number INTEGER DEFAULT(0),
OUT p_out_number INTEGER,
IN p_in_varchar VARCHAR(10) DEFAULT('0'),
OUT p_out_varchar VARCHAR(10),
IN p_in_date DATE DEFAULT('1981-07-10'),
OUT p_out_date DATE
)
With Oracle, I can discover defaults using this query:
SELECT argument_name, defaulted FROM all_arguments WHERE object_id = :proc_id
How can I discover this in DB2 selecting from SYSCAT tables? I don't see any useful column in SYSCAT.PROCPARMS or SYSCAT.FUNCPARMS. Note, I don't mind calling any stored procedure from SYSPROC if such a procedure exists...
Note, I have asked as similar question about SQL Server:
Discover SQL Server procedure default parameters using SYS or INFORMATION_SCHEMA tables

(This assumes you're looking for the information on DB2 Linux/Unix/Windows, it may vary for other platforms)
You can use the SYSCAT.ROUTINEPARMS catalog view to find this information. It lists all the parameter types that the function can accept (there can be multiple rows if the procedure has multiple signatures), and if applicable, their default (in the aptly-named DEFAULT column). If a default is not supplied, that column will be NULL.
For example, if you wanted to see the input parameters for SYSIBMADM.SUBMIT (which has optional parameters), you could use this query:
SELECT *
FROM SYSCAT.ROUTINEPARMS
WHERE ROUTINESCHEMA='SYSIBMADM'
AND ROUTINENAME ='SUBMIT'
AND ROWTYPE IN ('B', 'P')
ROWTYPE of B allows for both input and output variables, and P is for input-only. The other types are covered in the Info Center doc I linked above.

Related

DB2 creating temporal table creating column with CURRENT PACKAGESET or CLIENT_APPNAME

Does anyone know which of the DB2 special registers are allowed in CREATE TABLE statement for DB2 temporal tables or in general in CREATE TABLE statement?
I am trying to CREATE TABLE COLUMNS WITH CURRENT PACKAGESET or CLIENT_APPNAME, they are not being identified by DB2. I tried almost all combinations of key words (marked in bold).
Create table Statement
CREATE TABLE EMPLOYEE
(EMP_NR INT NOT NULL
,FIRST_NAME CHAR(20) NOT NULL
,LAST_NAME CHAR(20) NOT NULL
,TSROWBEGIN TIMESTAMP(12) NOT NULL GENERATED ALWAYS AS ROW BEGIN
,TSROWEND TIMESTAMP(12) NOT NULL GENERATED ALWAYS AS ROW END
,TSPGMSTART TIMESTAMP(12) NOT NULL GENERATED ALWAYS AS TRANSACTION START ID
**,IDTERMANV CHAR(8) GENERATED DEFAULT WITH CURRENT PACKAGESET
,IDTERM VARCHAR(128) GENERATED DEFAULT WITH CLIENT_APPLNAME**
,STDB2ACTION CHAR(1) GENERATED ALWAYS AS ( DATA CHANGE OPERATION )
,PERIOD SYSTEM_TIME(TSROWBEGIN, TSROWEND)
);
It results in
ILLEGAL USE OF KEYWORD CURRENT. TOKEN WAS EXPECTED. SQLCODE=-199, SQLSTATE=42601, DRIVER=3.68.61
or
ILLEGAL USE OF KEYWORD CLIENT_APPLNAME. TOKEN WAS EXPECTED. SQLCODE=-199, SQLSTATE=42601, DRIVER=3.68.61
Any suggestions on how to create column with default value of program name which is doing CUD operation on the table?
You can use the special registers for current date / time / timestamp and for user information (user, session user, system user). Take a look at the CREATE TABLE reference.
The same reference also has a section about what cannot be used, in case you try to use a function or put the CREATE statement into a procedure. Among other things, the GENERATED value cannot be based on the following:
Special registers and built-in functions that depend on the value of a special register.

How do I pass multiple entries through an input parameter mapped from a Table Function in SAP HANA

How do I pass multiple entries through an input parameter mapped from a Table Function in SAP HANA ?
I've written a Table Function with an Input Parameter say IN_FORMAT_CD.
I've mapped this parameter to the one created in my calculation view.
I'm able to retrieve the data when I'm passing only one value say 100.
But it gives no result when I'm passing more than one value.
Is there any workaround for the same ?
My table function :
FUNCTION "HADMIN"."RA.Test.Prathamesh::PH_DEMO" (IN IN_FORMAT_CD NVARCHAR(500))
RETURNS TABLE (NAME NVARCHAR(10), ID NVARCHAR(10), FORMAT_CD NVARCHAR(3))
LANGUAGE SQLSCRIPT
SQL SECURITY INVOKER AS
BEGIN
RETURN
SELECT NAME,ID,FORMAT_CD
FROM
HADMIN.PH_DEMO
WHERE FORMAT_CD IN (select :IN_FORMAT_CD as FORMAT_CD from dummy);
END;
What you are looking for is the APPLY_FILTER function of SAP HANA SQLScript.
The following example shows how your scenario could be coded:
create function get_vals (IN id_list varchar(400))
returns table (id bigint, val varchar(40))
as
begin
declare myfilter varchar(450) := ' ID in (' || :id_list || ')';
_tmp = select id, val from some_vals;
_tmp2 = APPLY_FILTER (:_tmp, :myfilter);
return :_tmp2;
end;
select *
from
get_vals ('1, 4, 23, 4, 23, 3');
This approach will push down the unique list of IDs to be used as a filter when reading the table data. However, this is still dynamic SQL so you lose benefits like plan sharing and risk SQL injection attacks. Read more on this e.g. here.
If possible, you want to handle selection lists in your application code.
This, in turn, would also give you the option to decide whether using IN-lists or inner joins against temporary tables is the best approach for your situation.
In case you want to go with the selection list as a string, you should at least make sure, that common SQL injection attacks are not used and that the "in-list" really only contains possible ID values and commas.
it is not possible to produce(!) many items from a single sql variable unless you split them
In your SQL subselect query will return only rows that FORMAT_CD column values are exactly same with IN_FORMAT_CD parameter.
If this parameter represents more than one value, then this parameter is a concatenated string representation of each sub items. So we can split them back.
Splitting will produce a table on the fly which can be used for selection.
Please create the user-defined HANA Split function fnsplit that source codes can be found at referenced document
Then you can alter your function as follows assuming that each value is seperated with "," from others
ALTER FUNCTION "HADMIN"."RA.Test.Prathamesh::PH_DEMO" (IN IN_FORMAT_CD NVARCHAR(500))
RETURNS TABLE (NAME NVARCHAR(10), ID NVARCHAR(10), FORMAT_CD NVARCHAR(3))
LANGUAGE SQLSCRIPT
SQL SECURITY INVOKER AS
BEGIN
RETURN
SELECT NAME,ID,FORMAT_CD
FROM
HADMIN.PH_DEMO
WHERE FORMAT_CD IN (
select str from fnsplit(:IN_FORMAT_CD,',')
);
END;

INPUT a List to stored procedure

I get a list of elments from R and I have to obtain the records from database that belong to a the list of elements.
INPUT:
'12345','23456', '34567', '45678'
PROCEDURE:
CREATE PROCEDURE "SCHEMA"."GET_RECORDS" (IN LIST (Type), OUT RECORDS tt_records)
LANGUAGE SQLSCRIPT
SQL SECURITY INVOKER
READS SQL DATA AS
BEGIN
RECORDS = select * from TABLE where ids in :LIST
END;
How can I provide such a list to the proceudre?
Handing over lists of parameters to SQLScript is a bit tricky as there is no straight-forward native construct for that.
One way to do it is to use the APPLY_FILTER function and to "smuggle" the list as a string parameter.
In my example I read from a table CUSERS and I create a filter condition for APPLY_FILTER that filters column USER_ID via an IN ( ) clause.
Removing the single quotes (' ') from the list is to avoid implicit type conversion when executing the query. Leaving the single quotes in place would make the IN () clause make look like this:
IN ( '<1st value>', '<2nd value>', '<3rd value>', ...)
instead of
IN (<1st value>, <2nd value>, <3rd value>, ...).
CREATE PROCEDURE "GET_RECORDS" (IN id_list VARCHAR(4000)
, OUT RECORDS tt_cusers)
LANGUAGE SQLSCRIPT
SQL SECURITY INVOKER
READS SQL DATA AS
BEGIN
declare _filter VARCHAR(4000);
_users = select * from cusers;
-- APPLY_FILTER expects a proper WHERE condition, so adding the column to filter
-- and the IN () expression is necessary.
--
-- the the id_list comes in with single quotes, let's remove those
_filter = 'USER_ID in (' || replace (:id_list, '''', '') ||')';
RECORDS = APPLY_FILTER(:_users, :_filter);
end;
call get_records (?, ?)
-- this 'list' is to be used as a single parameter value
-- '131072', '161223', '131074'
A slightly more comfortable approach for getting the data out from SAP HANA into R can be using a table typed user-defined function (UDF) instead. The main difference here is that the calling statement is a simple SELECT and the result is simply the resultset of this SELECT.
CREATE function "FGET_RECORDS" (IN id_list VARCHAR(4000))
returns tt_cusers
LANGUAGE SQLSCRIPT
SQL SECURITY INVOKER
READS SQL DATA AS
BEGIN
declare _filter VARCHAR(4000);
_users = select * from cusers;
-- APPLY_FILTER expects a proper WHERE condition, so adding the column to filter
-- and the IN () expression is necessary.
--
-- the the id_list comes in with single quotes, let's remove those
_filter = 'USER_ID in (' || replace (:id_list, '''', '') ||')';
_result = APPLY_FILTER(:_users, :_filter);
RETURN :_result;
end;
select * from fget_records (? );
In R (or in any other client) make sure to use bind variables when using this construct. Otherwise handling the different string quote-mechanisms can become cumbersome.
See the documentation on APPLY_FILTER here.
Use a User Defined Data Type.
First Create A User Defined Data Type
Database Node > Programmability > Types > User-Defined Table Types
Script :
CREATE TYPE dbo.MyTableType AS TABLE
(
ID INT
)
Create a Parameter in your procedure with the above type
CREATE PROCEDURE usp_InsertMessages
(
#MyParameter MyTableType READONLY
)
AS
BEGIN
INSERT INTO MyTable
(
id
)
SELECT
id
FROM #MyParameter
END

Discover SQL Server procedure default parameters using SYS or INFORMATION_SCHEMA tables

Like Oracle, SQL Server supports parameter defaults in stored procedures. Oracle syntax:
CREATE OR REPLACE PROCEDURE p_default (
p_in_number IN number := 0,
p_out_number OUT number,
p_in_varchar IN varchar2 := '0',
p_out_varchar OUT varchar2,
p_in_date IN date := date '1981-07-10',
p_out_date OUT date
)
SQL Server syntax:
CREATE PROCEDURE p_default (
#p_in_number INTEGER = 0,
#p_out_number INTEGER OUT,
#p_in_varchar VARCHAR(10) = '0',
#p_out_varchar VARCHAR(10) OUT,
#p_in_date DATE = '1981-07-10',
#p_out_date DATE OUT
)
With Oracle, I can discover defaults using this query:
SELECT argument_name, defaulted FROM all_arguments WHERE object_id = :proc_id
How can I discover this in SQL Server selecting from sys or INFORMATION_SCHEMA tables? I don't see any useful column in INFORMATION_SCHEMA.PARAMETERS, and the sys.parameters.has_default_value seems not to be set correctly (!)
Note, I have asked as similar question about DB2:
Discover DB2 procedure default parameters using SYSCAT tables
There's no simple way to do it. As the documentation for has_default_value states:
SQL Server only maintains default values for CLR objects in this catalog view; therefore, this column has a value of 0 for Transact-SQL objects. To view the default value of a parameter in a Transact-SQL object, query the definition column of the sys.sql_modules catalog view, or use the OBJECT_DEFINITION system function.
So you'd have to pull the whole stored proc definition out and parse it yourself to determine the value.
Side note: I'd be wary of #p_in_date DATE = '1981-07-10'. I know that the date datatype is a bit more sensible than datetime, but I'm not sure if the above is still ambiguous - certainly if it was converted to datetime, it may result in 10th July or 7th October, depending on language settings. I'd be more comfortable with '19810710' which will always be interpreted as 10th July.

Informix: Select null problem

Using Informix, I've created a tempory table which I am trying to populate from a select statement. After this, I want to do an update, to populate more fields in the tempory table.
So I'm doing something like;
create temp table _results (group_ser int, item_ser int, restype char(4));
insert into _results (group_ser, item_ser)
select
group_ser, item_ser, null
from
sometable
But you can't select null.
For example;
select first 1 current from systables
works but
select first 1 null from systables
fails!
(Don't get me started on why I can't just do a SQL Server like "select current" with no table specified!)
You don't have to write a stored procedure; you simply have to tell IDS what type the NULL is. Assuming you are not using IDS 7.31 (which does not support any cast notation), you can write:
SELECT NULL::INTEGER FROM dual;
SELECT CAST(NULL AS INTEGER) FROM dual;
And, if you don't have dual as a table (you probably don't), you can do one of a few things:
CREATE SYNONYM dual FOR sysmaster:"informix".sysdual;
The 'sysdual' table was added relatively recently (IDS 11.10, IIRC), so if you are using an older version, it won't exist. The following works with any version of IDS - it's what I use.
-- #(#)$Id: dual.sql,v 2.1 2004/11/01 18:16:32 jleffler Exp $
-- Create table DUAL - structurally equivalent to Oracle's similarly named table.
-- It contains one row of data.
CREATE TABLE dual
(
dummy CHAR(1) DEFAULT 'x' NOT NULL CHECK (dummy = 'x') PRIMARY KEY
) EXTENT SIZE 8 NEXT SIZE 8;
INSERT INTO dual VALUES('x');
REVOKE ALL ON dual FROM PUBLIC;
GRANT SELECT ON dual TO PUBLIC;
Idiomatically, if you are going to SELECT from Systables to get a single row, you should include 'WHERE tabid = 1'; this is the entry for Systables itself, and if it is missing, the fact that your SELECT statement does return any data is the least of your troubles. (I've never seen that as an error, though.)
This page says the reason you can't do that is because "NULL" doesn't have a type. So, the workaround is to create a sproc that simply returns NULL in the type you want.
That sounds like a pretty bad solution to me though. Maybe you could create a variable in your script, set it to null, then select that variable instead? Something like this:
DEFINE dummy INT;
LET dummy = NULL;
SELECT group_ser, item_ser, dummy
FROM sometable
SELECT group_ser, item_ser, replace(null,null) as my_null_column
FROM sometable
or you can use nvl(null,null) to return a null for your select statement.
Is there any reason to go for an actual table? I have been using
select blah from table(set{1})
select blah from table(set{1})
is nice when you are using 10.x database. This statement doesn't touch database. The amount of read/write operations is equal to 0,
but
when you're using 11.x it will cost you at least 4500 buffer reads because this version of Informix creates this table in memory and executes query against it.
select to_date(null) from table;
This works when I want to get a date with null value
You can use this expression (''+1) on the SELECT list, instead of null keyword. It evaluates to NULL value of type DECIMAL(2,0).
This (''+1.0001) evaluates to DECIMAL(16,4). And so on.
If you want DATE type use DATE(''+1) to get null value of type DATE.
(''+1)||' ' evaluates to an empty string of type VARCHAR(1).
To obtain NULL value of type VARCHAR(1) use this expression:
DATE(''+1)||' '
Works in 9.x and 11.x.