How to execute an SQL string in DB2 - db2

How do I execute an SQL string statement in DB2? I'm using IBM Data Studio.

Do you mean executing a dynamic SQL string? Something like:
DECLARE stmt VARCHAR(1000);
DECLARE my_table VARCHAR(50);
SET my_table = 'DEPT_'||deptNumber;
SET stmt = 'SELECT * FROM '||my_table;
PREPARE s1 FROM stmt;
EXECUTE s1;
You can only do that in a stored proc though. One defined as CREATE PROCEDURE GetDeptInfo (deptNumber VARCHAR(5)) for this example. Read about EXECUTE and PREPARE in the db2 docs http://publib.boulder.ibm.com/infocenter/db2luw/v9r5/index.jsp

After days of researching I found how to write and run dynamic SQL on DB2:
create or replace procedure Search ()
BEGIN
DECLARE v_dynamicSql varchar(2000);
SET v_dynamicSql = 'INSERT INTO dictonary(name) values(' || 'dynamicSQL in db2' ||')';
EXECUTE IMMEDIATE v_dynamicSql;
END;
Hope to help someone.

What difficulty are you encountering?
There are likely lots of ways to do it. Here's one:
File -> New -> Other -> SQL or XQuery script
You may need to create a project or define a database connection.
Enter the SQL code.
Script -> Run script.
Results will show up at the bottom of your screen.

In Control Center, right click the database, you will see "Query". Click on it and you are good to go.

Related

Stored procedure in Redshift to use string replacement with unload

I want to achieve something among the following lines:
create or replace procedure my_sp_name(p_date date) as
$$
begin
unload ('
select *
from my_table
where my_date = ''DATE_GOES_HERE''
')
to 's3://my-bucket/some_key/DATE_GOES_HERE/some_file'
iam_role 'my_iam_role'
allowoverwrite csv parallel off;
end ;
$$
language plpgsql;
I have been trying different things, however, can't seem to find what is the correct way to to do the string replacement in both parts of the unload. What is the correct way of doing this?
You need to EXECUTE "SQL statement" in the procedure. See: https://docs.aws.amazon.com/redshift/latest/dg/c_PLpgSQL-statements.html under "dynamic SQL" section.

How can I pass a SQL to Cursor which is coming as string in DB2?

I want to pass a SQL to my stored proc as input as a string and my stored proc will pass this SQL as a string to a cursor and provide the output. But a Cursor doesn't accept a SQL as string and we need to prepare the SQL statement and then pass it onto the Cursor. I am not able to make that part working. Please find my sample code here :
Create Procedure abc(IN stmt VARCHAR(500))
SPECIFIC abc
LANGUAGE SQL
DYNAMIC RESULT SETS 1
Re: BEGIN
DECLARE Instmt VARCHAR(500)
PREPARE Instmt FROM stmt;
EXECUTE Instmt;
DECLARE v_cur CURSOR WITH RETURN FOR Instmt;
OPEN v_cur;
END Re
--call abc('select ename,sal from emp')
It gives me error as such that Cursor is expecting a SQL statement. So more or less I am not able to PREPARE the SQL properly to feed it to the CURSOR.
Error Message:
SQL0104N "An expected token "" was found following "".Expected token may include: ""
Please let me know how I could get it working.
Try this one
--#SET TERMINATOR #
CREATE OR REPLACE PROCEDURE TEST_PROC(IN stmt VARCHAR(500))
SPECIFIC TEST_PROC
LANGUAGE SQL
DYNAMIC RESULT SETS 1
BEGIN
DECLARE test_cur CURSOR WITH RETURN TO CALLER FOR test_stmt;
PREPARE test_stmt FROM stmt;
OPEN test_cur;
END#

How to create a stored procedure including the "SELECT" in Oracle SQL Developer?

I am novice user in oracle and well I am creating a stored procedure to display data from a table, because my teaching process requires it. At first I ran my query follows.
Create or replace procedure p_ mostrar
Is
Begin
Select ID_MODULO, NOMBRE, URL, ESTADO, ICONO FROM MODULO WHERE ESTADO=1 ;
Commit;
End p_mostrar;
And he throws me the following error:
The judgment was expected INTO" After some research changed the syntax and run it as follows:
Create or replace procedure p_ mostrar (C1 out sys_refcursor)
Is
Begin Open C1 for Select ID_MODULO, NOMBRE, URL, ESTADO, ICONO
FROM MODULO
WHERE ESTADO=1 ;
Commit;
End p_mostrar;
And I think runs correctly. But now it does not know how to run the procedure. I thank you in advance and expect a prompt response. Remember, I'm learning with Oracle SQL Developer.
When you are dealing with select statement inside a stored procedure, you need to include INTO clause to the select statement to store the values in a variable. Try this
CREATE OR REPLACE PROCEDURE p_mostrar
IS
v_id_modulo modulo.id_modulo%TYPE;
v_nombre modulo.nombre%TYPE;
v_url modulo.url%TYPE;
v_estado modulo.estado%TYPE;
v_icono modulo.icono%TYPE;
BEGIN
SELECT id_modulo, nombre, url, estado, icono
INTO v_id_modulo, v_nombre, v_url, v_estado, v_icono --needed to catch the values selected and store it to declared variables
FROM modulo
WHERE estado=1 ;
Commit; -- i dont think this is necessary, you use commit statement only when you use DML statements to manage the changes made
dbms_output.put_line(v_id_modulo||' '|| v_nombre||' '||v_url||' '||v_estado||' '||v_icono); --used to display the values stored in the variables
END;
This should work:
var result refcursor
execute p_ mostrar(:result)

dynamic sql query in postgres

I was attempting to use Dynamic SQL to run some queries in postgres.
Example:
EXECUTE format('SELECT * from result_%s_table', quote_ident((select id from ids where condition = some_condition)))
I have to query a table, which is of the form result_%s_table wherein, I need to substitute the correct table name (an id) from an another table.
I get the error ERROR: prepared statement "format" does not exist
Link: string substitution with query result postgresql
EXECUTE ... USING only works in PL/PgSQL - ie within functions or DO blocks written in the PL/PgSQL language. It does not work in plain SQL; the EXECUTE in plain SQL is completely different, for executing prepared statements. You cannot use dynamic SQL directly in PostgreSQL's SQL dialect.
Compare:
PL/PgSQL's EXECUTE ... USING; to
SQL's EXECUTE
See the 2nd last par in my prior answer.
In addition to not running except in PL/PgSQL your SQL statement is wrong, it won't do what you expect. If (select id from ids where condition = some_condition) returns say 42, the statement would fail if id is an integer. If it's cast to text you'd get:
EXECUTE format('SELECT * from result_%s_table', quote_ident('42'));
EXECUTE format('SELECT * from result_%s_table', '"42"');
EXECUTE 'SELECT * from result_"42"_table';
That's invalid. You actually want result_42_table or "result_42_table". You'd have to write something more like:
EXECUTE format('SELECT * from %s', quote_ident('result_'||(select id from ids where condition = some_condition)||'_table'))
... if you must use quote_ident.
CREATE OR REPLACE FUNCTION public.exec(
text)
RETURNS SETOF RECORD
LANGUAGE 'plpgsql'
AS $BODY$
BEGIN
RETURN QUERY EXECUTE $1 ;
END
$BODY$;
usage:
select * from exec('select now()') as t(dt timestamptz)
Try using
RETURN QUERY EXECUTE '<SQL Command>'
This will return data into form of table. You have to use this into stored function of PostgreSQL.
I have already created on full demonstration on custom filter and custom sorting using dynamic query of PostgreSQL.
Please visit this url:
http://www.dbrnd.com/2015/05/postgresql-dynamic-sql/
These all look more complicated than the OP's question. A different formatting should do the trick.. but it could absolutely the case that I don't understand.
From how I read OP's question, I think others in a similar situation may benefit from how I got it.
I am using Postgre on Redshift, and I ran into this issue and found a solution.
I was trying to create a dynamic query, putting in my own date.
date = dt.date(2018, 10, 30)
query = ''' select * from table where date >= ''' + str(my_date) + ''' order by date '''
But, the query entirely ignores the condition when typing it this way.
However, if you use the percent sign (%), you can insert the date correctly.
One correct way to write the above statement is:
query = ''' select * from table where date >= ''' + ''' '%s' ''' % my_date + ''' order by date '''
So, maybe this is helpful, or maybe it is not. I hope it helps at least one person in my situation!
Best wishes.
EXECUTE will work only on pl/pqsql environment.
instead of EXECUTE try with SELECT
SELECT format('SELECT * from result_%s_table', quote_ident((select id from ids where condition = some_condition))
output would be the dynamic query.

DB2 compound statement using ADO.NET

I want to execute multiple statements from my data access layer using C# dan IBM's DB2 data provider.
(environment: DB2/AS400 os version: V5R4)
eg in TSQL:
declare varA integer;
select varA= count(*) from tableA;
select * from tableB where col1 <= varA
with SQL server ; I can concatenate those 3 statements into a string
and assign the text to DBCommand.CommandText.
How to execute multiple statements(compound statement) against DB2 database via DBCommand (using IBM DB2 data provider)
I tried using begin and end block but still failed
BEGIN
statement1;
statement2;
statement3;
END
Thank you
I do not think it's possible.
I had already tried something similar some time ago, and the only solution I found is to dynamically create a stored procedure, calling it, and finally delete it.