how to fix parameters for sqlquery in lazarus - lazarus

I'm trying to make a program in lazarus that should create a table in mysql.
Below the code I wrote:
sqlquery2.SQL.AddText('CREATE TABLE `oferte`.:id (`idnew_table` INT NOT NULL, PRIMARY KEY (`idnew_table`));');
sqlquery2.Params.ParamByName('id').asstring:=client.text;
When I launch this code, I got the following error:
"You have an error into your sql syntax..."
I have tried:
sqlquery2.SQL.AddText('CREATE TABLE `oferte`.`test1` (`idnew_table` INT NOT NULL, PRIMARY KEY (`idnew_table`));');
The program is running as expected and the table is created into the database with no error.
I also wrote a code with param passing in sql for inserting data into a table and it worked fine.
The code that I run which is OK:
sqlquery1.sql.Clear;
sqlquery1.SQL.Text:='insert into stocpiese(denumire,stoc,furnizor,client,pretintrare,adaoscom,'+'cod,pretiesire, moneda ,schimbvalutar,datacumpararii)'+'values ( (:den),(:stoc),(:furn),(:client),(:pretin),(:adcom),'+'(:cod),(:preties),(:moneda),(:schimb),(:data));';
sqlquery1.Params.ParamByName('den').AsString:=denumire.text;
sqlquery1.Params.ParamByName('stoc').AsString:=stoc.text;
sqlquery1.Params.ParamByName('furn').AsString:=furnizorsele.text;
sqlquery1.Params.ParamByName('client').AsString:=clientsele.text;
sqlquery1.Params.ParamByName('pretin').AsString:=pretintrare.text;
sqlquery1.Params.ParamByName('adcom').AsString:=adcom.text;
sqlquery1.Params.ParamByName('cod').AsString:=codsele.text;
sqlquery1.Params.ParamByName('preties').AsString:=pretiesire.text;
sqlquery1.Params.ParamByName('moneda').AsString:='lei';
sqlquery1.Params.ParamByName('schimb').AsString:=edit3.text;
sqlquery1.Params.ParamByName('data').AsString:=FormatDateTime('dd-mm-yy', data+201);
if(MySQL57Connection1.connected=false)then MySQL57Connection1.connected:=true;
if(SQLTransaction1.active=false)then SQLTransaction1.active:=true;
sqlquery1.ExecSQL;
SQLTransaction1.CommitRetaining;
sqlquery1.Open;
I do not understand, am I missing something?

You can create a stored procedure like this:
DELIMITER $$
CREATE PROCEDURE `create_my_table`(IN `table_name` TEXT)
BEGIN
SET #s=CONCAT('CREATE TABLE IF NOT EXISTS ',
`table_name`,
' (
`idnew_table` INT NOT NULL, PRIMARY KEY (`idnew_table`)
)
);
PREPARE stmt FROM #s;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
END $$
DELIMITER ;
and then pass any string (or parameter) when calling it:
CALL create_my_table("anything");
You can also see my answer here

Related

create a random uuid function and use it to generate column value in oracle [duplicate]

I am trying to update a table in Oracle. The table is created using following DDL:
CREATE TABLE TEST (
ID_NUM INTEGER,
NAME INTEGER,
VALUE INTEGER,
ITEMS_NUM INTEGER,
)
And there were some data injected into this table. Now, I need to update the table to change the ID_NUM column as VARCHAR and add formatted UUID as default value.
I have followed the queries given below:
CREATE OR REPLACE FUNCTION RANDOM_UUID RETURN VARCHAR IS
V_UUID VARCHAR(255);
BEGIN
SELECT REGEXP_REPLACE(RAWTOHEX(SYS_GUID()), '([A-F0-9]{8})([A-F0-9]{4})([A-F0-9]{4})([A-F0-9]{4})([A-F0-9]{12})', '\1-\2-\3-\4-\5') INTO V_UUID FROM DUAL;
RETURN V_UUID;
END RANDOM_UUID;
ALTER TABLE TEST
DROP COLUMN ID_NUM;
ALTER TABLE TEST
ADD ID_NUM VARCHAR(255) DEFAULT random_uuid() NOT NULL;
It gives an error as SQL Error [4044] [42000]: ORA-04044: procedure, function, package, or type is not allowed here
I have executed and validated the function using following command and it gives a valid formatted UUID.
SELECT RANDOM_UUID() FROM DUAL;
What could be the issue in the ALTER table statement. Can't we use a function for setting default value in Oracle?
Thanks in advance.
I think you can achieve it using the default clause on the column but without function (just replace the function call with the content of the function in default clause) as following. (Please note that the User functions are not allowed in the default clause)
ALTER TABLE TEST
ADD ID_NUM VARCHAR(255)
DEFAULT REGEXP_REPLACE(RAWTOHEX(SYS_GUID()), '([A-F0-9]{8})([A-F0-9]{4})([A-F0-9]{4})([A-F0-9]{4})([A-F0-9]{12})', '\1-\2-\3-\4-\5')
NOT NULL;
I have prepared the db<>fiddle demo to show you the error with function and success without function.
Cheers!!
You cannot use PL/SQL functions in the default expression. But it can be a SQL function.Here's an extract from the 19c Doc:
Default column values are subject to the following restrictions:
A DEFAULT expression cannot contain references to PL/SQL functions or
to other columns, the pseudocolumns LEVEL, PRIOR, and ROWNUM, or date
constants that are not fully specified.
And here's an example using a sql function:
SQL> create table tc (c1 number default sqrt(2));
Table TC created.
The default value has to be an actual value, not a function.

PL/SQL reusable dynamic sql program for same type of task but different table and column

Thank you for reply guys. I kind of solved my problem.
I used to try to update data with ref cursor in dynamic SQL using "where current of" but I now know that won't work.
Then I tried to use %rowtype to store both 'id' and 'clob' in one variable for future updating but turns out weak ref cursor can't use that type binding either.
After that I tried to use record as return of an ref cursor and that doesn't work on weak cursor either.
On the end, I created another cursor to retrieve 'id' separately along with cursor to retrieve 'clob' on the same time then update table with that id.
I'm now working on a Oracle data cleaning task and have a requirement like below:
There are 38 tables(maybe more in the future) and every table has one or multiple column which type is Clob. I need to find different keyword in those columns and according to a logic return binary label of the column and store it in a new column.
For example, there is a table 'myTable1' which has 2 Clob columns 'clob1' and 'clob2'. I'd like to find keyword 'sky' from those columns and store '0'(if not found) or '1'(if found) in two new columns 'clob1Sky','clob2Sky'.
I know if I could write it on a static way which will provide higher efficiency but I have to modify it for those very similar tasks every time. I want save some time on this so I'm trying to write it in a reusable way and not binding to certain table.
But I met some problem when writing the program. My program is like below:
create or replace PACKAGE body LABELTARGETKEYWORD
as
/**
#param varcher tableName: the name of table I want to work on
#param varchar colName: the name of clob column
#param varchar targetWord: the word I want to find in the column
#param varchar newColName: the name of new column which store label of clob
*/
PROCEDURE mainProc(tableName varchar, colName varchar,targetWord varchar,newColName varchar2)
as
type c_RecordCur is ref cursor;
c_sRecordCur c_recordCur;
/*other variables*/
begin
/*(1) check whether column of newColName exist
(2) if not, alter add table of newColName
(3) open cursor for retrieving clob
(4) loop cursor
(5) update set the value in newColName accroding to func labelword return
(6) close cursor and commit*/
end mainProc;
function labelWord(sRecord VARCHAR2,targetWord varchar2) return boolean...
function ifColExist(tableName varchar2,newColName varchar2) return boolean...
END LABELTARGETKEYWORD;
Most DML and DDL are written in dynamic sql way.
The problem is when I write the (5) part, I notice 'Where current of' clause can not be used in a ref cursor or dynamic sql statement. So I have to change the plan.
I tried to use a record(rowid,label) to store result and alter the table later.(the table only be used by two people in my group, so there won't be problem of lock and data changes). But I find because I'm trying to use dynamic sql so actually I have to define ref cursor with return of certain %rowtype and basically all other variables, %type in dynamic sql statement. Which makes me feel my method has something wrong.
My question are:
If there a way to define %type in dynamic sql? Binding type to variable in dynamic SQL?
Could anybody give me a hint how to write that (5) part in dynamic SQL?
Should not I design my program like that?
Is it not the way how to use dynamic SQL or PLSQL?
I'm very new to PL/SQL. Thank you very much.
According to Tom Kyte's advice, to do it in one statement if it can be done in one statement, I'd try to use a single UPDATE statement first:
CREATE TABLE mytable1 (id NUMBER, clob1 CLOB,
clob2 CLOB, clob1sky NUMBER, clob2sky NUMBER )
LOB(clob1, clob2) STORE AS SECUREFILE (ENABLE STORAGE IN ROW);
INSERT INTO mytable1(id, clob1, clob2)
SELECT object_id, object_name, object_type FROM all_objects
WHERE rownum <= 10000;
CREATE OR REPLACE
PROCEDURE mainProc(tableName VARCHAR2, colName VARCHAR2, targetWord VARCHAR2, newColName VARCHAR2)
IS
stmt VARCHAR2(30000);
BEGIN
stmt := 'UPDATE '||tableName||' SET '||newColName||'=1 '||
'WHERE DBMS_LOB.INSTR('||colName||','''||targetWord||''')>1';
dbms_output.put_line(stmt);
EXECUTE IMMEDIATE stmt;
END mainProc;
/
So, calling it with mainProc('MYTABLE1', 'CLOB1', 'TAB', 'CLOB1SKY'); fires the statement
UPDATE MYTABLE1 SET CLOB1SKY=1 WHERE DBMS_LOB.INSTR(CLOB1,'TAB')>1
which seems to do the trick:
SELECT * FROM mytable1 WHERE clob1sky=1;
id clob1 clob2 clob1sky clob2skiy
33 I_TAB1 INDEX 1
88 NTAB$ TABLE 1
89 I_NTAB1 INDEX 1
90 I_NTAB2 INDEX 1
...
I am not sure with your question-
If this job is suppose to run on daily or hourly basis ,running query through it will be very costly. One thing you can do - put all your clob data in a file and save it in your server(i guess it must be linux). then you can create a shell script and schedule a job to run gerp command and fetch your required value and "if found then update your table".
I think you should approaches problem another way:
1. Find all columns that you need:
CURSOR k_clobs
select table_name, column_name from dba_tab_cols where data_type in ('CLOB','NCLOB');
Or 2 cursor(you can build you query if you have more than 1 CLOB per table:
CURSOR k_clobs_table
select DISTINCT table_name from dba_tab_cols where data_type in ('CLOB','NCLOB');
CURSOR k_clobs_columns(table_namee varchar(255)) is
select column_name from dba_tab_cols where data_type in ('CLOB','NCLOB') and table_name = table_namee;
Now you are 100% that column you are checking is clob, so you don't have to worry about data type ;)
I'm not sure what you want achieve, but i hope it may help you.

ORA-02437: "primary key violated" - why can't I see duplicate ID in SQL Developer?

I would receive an error:
ORA-02437: cannot validate (%s.%s) - primary key violated
Cause: attempted to validate a primary key with duplicate values or null values
I found it was because I have a stored procedure that increments the ID, but it had failed to do so when it re-ran and had an error related to one of my datatypes. I found I now had a duplicate ID in my database table. All this made sense and I was able to easily rectify it with a DELETE FROM MyTable WHERE ID = x, where x was the offending duplicate ID. The problem I have is the only way I was able to even find the IDs that were duplicated is in the first place is because I did a SELECT * FROM MyTable WHERE ID = x -- where x was one greater than the last ID I could actually see. I found it just by an educated guess. So:
Why can't I see these duplicate IDs when I open the table in Oracle SQL Developer? It only shows the last row as the ID before the duplicates. I don't think it is because of my primary key constraint, since the first line in my stored procedure is to remove that (and put it back, at the end - probably when I got my error), and it was not present when I looked at my table.
Is there some way to make these last IDs that got inserted into the table visible, so I wouldn't have to guess or assume that the duplicate IDs are "hiding" as one greater than the last ID I have in my table, in the future? There is a commit; in my stored procedure, so they should have appeared -- unless, of course, the procedure got hung up before it could run that line of code (highly probable).
Stored procedure that runs:
create or replace
PROCEDURE PRC_MYTABLE_INTAKE(
, EMPLOYEE_ID IN NVARCHAR2
, TITLE_POSITION IN NVARCHAR2
, CREATED_DATE IN DATE
, LAST_MODIFIED IN DATE
) AS
myid integer := 0;
appid integer := 0;
BEGIN
-- disable PK constraint so it can be updated
EXECUTE IMMEDIATE 'ALTER TABLE MYTABLE DROP CONSTRAINT MYTABLE_PK';
COMMIT;
-- assign ID to myid
SELECT ID INTO myid FROM MYTABLE WHERE ROWID IN (SELECT MAX(ROWID) FROM MYTABLE);
-- increment
myid := myid + 1;
-- assign APPLICATION_ID to appid
SELECT APPLICATION_ID INTO appid FROM MYTABLE WHERE ROWID IN (SELECT MAX(ROWID) FROM MYTABLE);
-- increment
appid := appid + 1;
-- use these ids to insert with
INSERT INTO MYTABLE (ID, APPLICATION_ID,
, EMPLOYEE_ID
, TITLE_POSITION
, CREATED_DATE
, LAST_MODIFIED
) VALUES(myid, appid,
, EMPLOYEE_ID
, TITLE_POSITION
, CREATED_DATE
, LAST_MODIFIED
);
COMMIT;
-- re-enable the PK constraint
EXECUTE IMMEDIATE 'ALTER TABLE PASS ADD CONSTRAINT MYTABLE_PK PRIMARY KEY (ID)';
COMMIT;
END;
Here's one problem:
SELECT ID
INTO myid
FROM MYTABLE
WHERE ROWID IN (SELECT MAX(ROWID) FROM MYTABLE)
There is no correlation between ID and ROWID, so you're not getting the maximum current ID, you're just getting the one that happens to be on the row that is furthest from the start of a datafile with a high number.
The code you need is:
SELECT COALESCE(MAX(ID),0)
FROM MYTABLE;
Or better yet, just use a sequence.
No idea why you're dropping the PK either.
Furthermore, when you issue the query:
SELECT APPLICATION_ID INTO appid ...
... that could be for a different row than the one you already got the id for, because a change could have been committed to the table.
Of course another issue is that you can't run two instances of this procedure at the same time either.
For David Aldridge, since he wants to look at code instead of the real reason I posted my question, run this ---
CREATE TABLE YOURSCHEMA.TESTING
(
TEST_ID NVARCHAR2(100) NOT NULL
, TEST_TYPE NVARCHAR2(100) NOT NULL
, CONSTRAINT TEST_PK PRIMARY KEY
(
TEST_ID
)
ENABLE
);
create or replace
PROCEDURE PRC_TESTING_INSERT(
TEST_TYPE IN NVARCHAR2
) AS
testid integer := 0;
BEGIN
-- disable PK constraint so it can be updated
EXECUTE IMMEDIATE 'ALTER TABLE TESTING DROP CONSTRAINT TEST_PK';
COMMIT;
-- assign TEST_ID to testid
SELECT TEST_ID INTO testid FROM TESTING WHERE ROWID IN (SELECT MAX(ROWID) FROM TESTING);
-- increment
testid := testid + 1;
-- use this id to insert with
INSERT INTO TESTING (TEST_ID, TEST_TYPE) VALUES(testid, TEST_TYPE);
COMMIT;
-- re-enable the PK constraint
EXECUTE IMMEDIATE 'ALTER TABLE TESTING ADD CONSTRAINT TEST_PK PRIMARY KEY (TEST_ID)';
COMMIT;
END;
SET serveroutput on;
DECLARE
test_type varchar(100);
BEGIN
test_type := 'dude';
YOURSCHEMA.PRC_TESTING_INSERT(test_type);
-- to verify the variable got set and procedure ran, could do:
--dbms_output.enable;
--dbms_output.put_line(test_type);
END;
Now, because there is no data in the table, the stored procedure will fail with ORA-06512: no data found. If you then try and run it again, you will get ORA-02443: cannot drop constraint - nonexistent constraint, because the EXECUTE IMMEDIATE 'ALTER TABLE TESTING DROP CONSTRAINT TEST_PK'; successfully dropped it, and the procedure never ran the command at the end to re-add it. This is what made me think I needed the commits, but even without them, it still will not complete the whole procedure.
To prove that the procedure DOES run, if given proper data, run this after creating the table, but before creating/running the stored procedure:
INSERT INTO TESTING (TEST_ID, TEST_TYPE)
VALUES ('1', 'hi');
And if you run the proc from a new table (not one with its constraint dropped), it will run fine.
Since mathguy didn't post this as the answer, though I'll credit him for the information...
Answer to why I can't see the duplicates is because the COMMIT does not occur in the procedure when it failed due to a datatype mismatch (which we found was actually in the application's code that sent the variable's values into this procedure, not in the stored procedure, itself). (It's also why I'll mark down anyone that says you don't have to add so many COMMIT lines in this procedure.) The commands were run in the session of the user that starts it - in my case, another session of the same DB user I was logged in with, but started from my application, instead of my SQL Developer session. It also explains why I could do a COMMIT, myself, but it did not affect the application's session - I could not commit any actions ran from another session. Had I ran a COMMIT as an OracleCommand and did an .ExecuteNonQuery on my OracleConnection right after the failure within the catch of my application, I would have seen the rows in SQL Developer without having to do a special query.
So, in short, the only way to see the items was with a direct query using WHERE ID =, find the last ID and increment it, and put it in the query.

How to implement multi value parameter in spagoBi server

I made a birt report in spagoBI studio with multi_value parameter it works fine in studio.
But when i upload it to server it's execution give a blank page.
pls someone help me.
Has been a couple of years since the queston was asked but I thought I would post my experience with this issue as it may help others out there.
The problem is due to the fact that each value in the parameter string is being wrapped with single quotes so no where condition is met in your report's sql where statement.
So if you are using Postgresql see: https://www.spagoworld.org/jforum/posts/list/382.page. However if like me you are using MySQL then that where all the fun and games begin because MySQL does not have a ready to use regxp_split_to_table function! What worked for me was to use temporary tables and a stored procedure to return the report dataset. I then called the procedure in the report's queryString.
So the following were the steps I took:
create a function to split out each parameter from the multivalue String and remove the single quotes:
CREATE DEFINER=root#localhost FUNCTION SPLIT_STR(
x VARCHAR(255),
delim VARCHAR(12),
pos INT
) RETURNS varchar(255) CHARSET utf8
RETURN REPLACE(SUBSTRING(SUBSTRING_INDEX(x, delim, pos),
LENGTH(SUBSTRING_INDEX(x, delim, pos -1)) + 1),
delim, '')
Create a stored procedure to return the parameters as a resultset that can be matched via your sql's where in ($P{parameter}) statement. Thet trick here is to take the split and cleaned up parameter and insert it into a temporary table that can then be queried in the subsequent select statement that returns the dataset. My stored procedure looks like:
CREATE DEFINER=root#localhost PROCEDURE create_temp_breweries(fullstr varchar(255), startDate date, endDate date, outlet_Type varchar(255))
BEGIN
DECLARE a INT Default 0 ;
DECLARE b INT Default 0 ;
DECLARE str VARCHAR(255);
DECLARE outletStr VARCHAR(255);
drop temporary table if exists temp_table1;
create temporary table temp_breweries(col1 varchar(255));
drop temporary table if exists temp_table2;
create temporary table temp_outletTypes(col2 varchar(255));
loop1: LOOP
SET a=a+1;
SET str= REPLACE(SPLIT_STR(fullstr,",",a),'\'', '');
IF str='' THEN
LEAVE loop1;
END IF;
#Do Inserts into temp table here with str going into the row
insert into temp_table1 values (str);
END LOOP loop1;
loop2: LOOP
SET b=b+1;
SET outletStr= REPLACE(SPLIT_STR(outlet_Type,",",b),'\'', '');
IF outletStr='' THEN
LEAVE loop2;
END IF;
#Do Inserts into temp table here with outletStr going into the row
insert into temp_table2 values (outletStr);
# For testing: insert into mytest (brewery) values (outletStr);
END LOOP loop2;
SELECT [fields]
FROM
[tables]
WHERE
BINARY field IN (SELECT * FROM temp_table1)
AND DATE BETWEEN startDate AND endDate AND
BINARY field2 IN (SELECT * FROM temp_table2);
END
Got this from: MySQL Split Comma Separated String Into Temp Table.
I am sure there must be a better or easier way but this worked like a charm!

Oracle 11g - Is it possible to determine update or insert in a function / procedure?

I am working with Oracle 11g and I got a question.
What I want to do is :
make a procedure
when this procedure has called, it will move data form one table to the other (column is almost same, but has different primary key)
Since, they do not use same field as PK, it occurs an error if use insert statement only.
So I want to do if table has a key than update, otherwise insert.
i.e. DDL like follow. It has almost same, but pk.
create table Tbl_A (
a_pk number constraints pk_tbl_a primary key
, b_pk number
, some_text varchar2(10)
, created date
, changed date
);
create table Tbl_B (
a_pk number
, b_pk number constraints pk_tbl_b primary key
, some_text varchar2(10)
, created date
, changed date
);
Psuedo of what I want :
create or replace procedure mv_data
is
begin
case when [if Tbl_B has same b_pk] then [update statement] end
else [create statement] end;
commit;
end;
I know I can not use case when like above, but that what I am trying to achieve is something like that. MyBatis could be a solution, but the client want to this with only DB.(Actually, this job will be executed by Oracle DBMS_SCHEDULE)
Thanks for your kind answers :D
As an alternative to the MERGE solution as suggested by valentin you can use the following construction:
begin
-- try the insert
insert...
exception
when dup_val_on_index
then
update...
end;
You want to use MERGE
Some references:
https://oracle-base.com/articles/9i/merge-statement
http://psoug.org/reference/merge.html

Resources