How to create an update query with Open Office Base? - openoffice.org

I want to create basically an update query on Open Office Base (the same way with Ms ACCESS).

Base does not typically use update queries (but see below). Instead, the easiest way to do an update command is to go to Tools -> SQL. Enter something similar to the following, then press Execute:
UPDATE "Table1" SET "Value" = 'BBB' WHERE ID = 0
The other way is to run the command with a macro. Here is an example using Basic:
Sub UpdateSQL
REM Run an SQL command on a table in LibreOffice Base
Context = CreateUnoService("com.sun.star.sdb.DatabaseContext")
databaseURLOrRegisteredName = "file:///C:/Users/JimStandard/Desktop/New Database.odb"
Db = Context.getByName(databaseURLOrRegisteredName )
Conn = Db.getConnection("","") 'username & password pair - HSQL default blank
Stmt = Conn.createStatement()
'strSQL = "INSERT INTO ""Table1"" (ID,""Value"") VALUES (3,'DDD')"
strSQL = "UPDATE ""Table1"" SET ""Value"" = 'CCC' WHERE ID = 0"
Stmt.executeUpdate(strSQL)
Conn.close()
End Sub
Note that the data can also be modified with a form or by editing the table directly.
Under some circumstances it is possible to create an update query. I couldn't get this to work with the default built-in HSQLDB 1.8 engine, but it worked with MYSQL.
In the Queries section, Create Query in SQL View
Click the toolbar button to Run SQL Command directly.
Enter a command like the following:
update mytable set mycolumn = 'This is some text.' where ID = 59;
Hit F5 to run the query.
It gives an error that The data content could not be loaded, but it still performs the update and changes the data. To get rid of the error, the command needs to return a value. For example, I created this stored procedure in MYSQL:
DELIMITER $$
CREATE PROCEDURE update_val
(
IN id_in INT,
IN newval_in VARCHAR(100)
)
BEGIN
UPDATE test_table SET value = newval_in WHERE id = id_in;
SELECT id, value FROM test_table WHERE id = id_in;
END
$$
DELIMITER ;
Then this query in LibreOffice Base modifies the data without giving any errors:
CALL update_val(2,'HHH')
See also:
https://forum.openoffice.org/en/forum/viewtopic.php?f=5&t=75763
https://forum.openoffice.org/en/forum/viewtopic.php?f=61&t=6655
https://ask.libreoffice.org/en/question/32700/how-to-create-an-update-query-in-base-sql/
Modifying table entries from LibreOffice Base, possible?

Related

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.

SSIS Script Component Call Stored Procedure returns -1

I tried implementing a call to Stored proc and the proc returns ID which will used later.
Everytime I execute I get the out parameter as -1. Below is my sample code:
OleDbCommand sqlStrProc = new OleDbCommand();
sqlStrProc.Connection = dbConn;
sqlStrProc.CommandText = "dbo.insert_test";
sqlStrProc.CommandType = CommandType.StoredProcedure;
sqlStrProc.Parameters.Add("#p_TestID", OleDbType.Integer, 255).Direction = ParameterDirection.Output;
sqlStrProc.Parameters.Add("#p_TestName", OleDbType.VarChar).Value = "Test";
sqlStrProc.Parameters.Add("#p_CreatedBy", OleDbType.VarChar).Value = "Test";
int personID = sqlStrProc.ExecuteNonQuery();
Row.outPersonID = personID;
personID is always -1. What am I doing wrong here. Please help..!!
Below is the stored proc code
CREATE PROCEDURE [dbo].[INSERT_TEST]
#p_TestID int OUTPUT,
#p_TestName varchar (50),
#p_CreatedBy varchar (100)
AS
SET NOCOUNT ON
INSERT INTO Test(
TestName,
CreatedBy)
VALUES
( #p_TestName,
#p_CreatedBy)
SELECT #p_TestID = SCOPE_IDENTITY()
-1 could mean that the stored procedure failed to execute as desired and the transaction was rolled back. You may want to look for any truncation issues since you have different sizes for the 2 input parameters but are using the same input. Also I assume you have proper code to open and close connections etc?
-1 returned value is an error produced during the execution of your SP, this is due to the following reasons:
SP Structure: everytime you are executing the SP it tries to create it again while it already exists. so you have to either make it an ALTER PROCEDURE instead of CREATE PROCEDURE or do the following:
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[INSERT_TEST]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[INSERT_TEST]
GO
CREATE PROCEDURE [dbo].[INSERT_TEST]
#p_TestID int OUTPUT,
#p_TestName varchar (50),
#p_CreatedBy varchar (100)
AS
Database Connection (Table Name and Location): you have to specify withe the OLEDB the ConnectionString that connects you to the write DB. try to test the full Table path; like the following;
INSERT INTO [DATABASENAME].[SHCEMA].[TABELNAME](
Name,
CreatedBy)
VALUES
( #p_TestName,
#p_CreatedBy)
Define your SP as :
CREATE PROCEDURE [NAME]
AS
BEGIN
END
thought it is not a problem, but it is a proper way to write your SPs in terms of connection transactions,
Let me know if it works fine with you :)
Regrads,
S.ANDOURA

Inno setup: Pass parameter (user input) to sql using ADO

I am using ADO to connect to SQL server in my inno setup, which is working fine. I am also executing few scripts to create database,users,schemas etc.
I am getting the Database name from the user and i want the script to create the database based on the user input, hence inside the script i'm using $(DBNAME) to get the value as parameter. I tried using CreateParameter, which isn't working fine,[Im not sure if im using it correctly] is there any other option to achieve this?
My inno code:
if LoadStringFromFile(ExpandConstant('{app}')+ '\SQLScripts\SCRIPT-1_CREATE_DB.sql', SQLQuery) then
begin
ADOCommand.CommandText := SQLQuery;
ADOParameter := ADOCommand.CreateParameter('DBNAME', adChar,adparaminput,30);
ADOParameter.Value := 'Dynadbnew';
ADOCommand.Parameters.Append (ADOParameter);
ADOCommand.Execute(NULL, NULL, adCmdText or adExecuteNoRecords);
end;
Below is my sample .sql script
USE [master]
CREATE DATABASE $(DBNAME) ON PRIMARY
( NAME = N'WMSFBASEDB_Data', FILENAME = N'C:\MDF\$(DBNAME).MDF' , SIZE = 420352KB , MAXSIZE = UNLIMITED, FILEGROWTH = 10%)
LOG ON
( NAME = N'WMSFBASEDB_Log', FILENAME = N'C:\MDF\$(DBNAME)_1.LDF' , SIZE = 16824KB , MAXSIZE = UNLIMITED, FILEGROWTH = 10%)
ALTER DATABASE $(DBNAME) ADD FILEGROUP [FG_HIS1]
ALTER DATABASE $(DBNAME) ADD FILEGROUP [FG_HIS2]
ALTER DATABASE $(DBNAME) SET COMPATIBILITY_LEVEL = 100
Thanks in advance

Detecting and Using CURRENT SCHEMA in DB2 v8

I have a very big Stored Procedure in iSeries DB2 v8 which does the following:
Calls other stored procedures inside the same schema
Prepares dynamic sql statments from strings and runs them
Calls other functions from the same schema
Uses various tables from the same schema
My problem is that this Stored Procedure and the accompanying functions may change from that schema into another (ie. from 'superlib' to 'restorelib') and the whole code is currently hardcoded to run with the named schema.
What I want is to be able to do one of the two: either pass the name of the schema where everything is located via a parameter to the stored procedure, or have the stored procedure detect the name of the schema and use it to run itself.
This is a sample of my current code:
SELECT COUNT(*) INTO TotalNotDone FROM superlib.PROCESSTABLES WHERE PROCESS_FLAG < 1;
WHILE TotalNotDone > 0 DO
SET SQLLOOPSTMT = 'select name_to_proces from ' CONCAT SOURCELIBRARY CONCAT '.processtables where process_flag = 0' ;
PREPARE LOOPSTMT FROM SQLLOOPSTMT ;
OPEN LOOPCUR ;
FETCH LOOPCUR INTO TABLETOPROCESS ;
CALL superlib.SP_RESTORE_INSERTS ( SOURCELIBRARY , DESTLIBRARY , TABLETOPROCESS, P_STARTTIME ) ;
CLOSE LOOPCUR;
SELECT COUNT(*) INTO TotalNotDone FROM superlib.PROCESSTABLES WHERE PROCESS_FLAG < 1;
END WHILE ;
What I want is for NOT to have to write superlib inside the stored procedure to call or reference the tables i'm using and just have the Stored Procedure recognize it currently IS living in the schema superlib.
I've tried SET CURRENT SCHEMA = 'SUPERLIB'; and SET SCHEMA = 'SUPERLIB'; but neither works when calling the TABLES.
I've also changed the path when creating the Stored Procedure from:
SET PATH "QSYS","QSYS2","SYSPROC","SYSIBMADM","PROGUSER1" ;
to
SET PATH "QSYS","QSYS2","SYSPROC","SYSIBMADM","SUPERLIB" ;
but that apparently does nothing.
i believe you'll need to set the current path on the connection that calls the stored proc, not just when creating it.
see this: Weblogic: Call DB2 stored procedure without schema name (property currentSchema)
current path documentation here: http://publib.boulder.ibm.com/infocenter/db2luw/v8//topic/com.ibm.db2.udb.doc/admin/r0005877.htm

How to retrieve a value from a recordset that is not a return value or output parameter using vb6

I have a stored proc on an existing 3rd party application (SQL 2005) that I wish to interact with.
It is an insert statement followed by a select statement as follows;
Set #CustomerId = Cast(SCOPE_IDENTITY() As [int])
Select #CustomerId
Using VB6 how do I access the value of #CustomerID?
set rs = cmd.Execute
is not returning a resultset as expected...
[Edit]
rs.Fields.Count is 0.
Any attempt to access the resulting recordset, like rs(0).Value simply causes an "Item not found..." error.
I would guess that your stored procedure is returning more than one recordset.
If this is the case, you can use the NextRecordset() method to iterate through them.
MSDN:
If a row-returning command executes successfully but returns no records,
the returned Recordset object will be
open but empty. Test for this case by
verifying that the BOF and EOF
properties are both True.
If a non–row-returning command executes successfully, the returned
Recordset object will be closed, which
you can verify by testing the State
property on the Recordset.
When there are no more results, recordset will be set to Nothing.
This means I would suggest something like this to solve your problem:
Set rs = cmd.Execute
''# fetch the first value of the last recordset
Do Until rs Is Nothing
If rs.State = adStateOpen Then
If Not (rs.BOF And rs.EOF) Then
''# You can do a different sanity check here, or none at all
If rs.Fields(0).Type = adInteger Then
CustomerId = rs.Fields(0).Value
End If
End If
End If
Set rs = rs.NextRecordSet
Loop
MsgBox CustomerId

Resources