Groovy Sql to execute statements in a batch - sql

I am using Groovy Sql to fetch results. This is the output from my Linux box. Actually there are 2 statements involved sp_configure 'number of open partitions' and go see below
%isql -U abc -P abc -S support
1> sp_configure 'number of open partitions'
2> go
Parameter Name Default Memory Used Config Value
Run Value Unit Type
------------------------------ ----------- ----------- ------------
------------ -------------------- ----------
number of open partitions 500 5201 5000
5000 number dynamic
(1 row affected)
(return status = 0)
1>
I am using groovy code
def sql = Sql.newInstance("jdbc:abc:sybase://harley:6011;DatabaseName=support;",dbuname,dbpassword,Driver)
sql.eachRow("sp_configure 'number of open partitions'"){ row ->
/*println row.run_value*/
}
Is there a way to execute statements in batch?
I am using Sybase

Not sure if it will work, but you might be able to do:
sql.call("sp_configure 'number of open partitions'")
sql.eachRow("go"){ row ->
...
}

Have not actually tried this [yet] but:
sql.call("sp_configure 'number of open partitions'")
int[] updateCounts = sql.withBatch({
sql.eachRow("go"){ row ->
...
}
})
// check your updateCounts here for errors

Just try this
sql.eachRow("sp_configure 'number of open partitions'"){ row ->
println row.'Parameter Name'.trim }

Related

SQL - How to call a part of query conditionally

I need to write a SQL query like this:
do step1
do step2
do step3
- this step does a lot of stuffs: define variables, use some variables defined in step 1, query a lot of data into temporary table...
if(cond1)
if(cond2)
Begin
do step 4
call step 3 here
End
else
Begin
do step 5
End
else
Begin
call step 3 here
End
How to make step 3 a reusable query to avoid calling step 3 unnecessarily? notice that step 3 should be a part of the whole query
When I try to create a #step3Query NVARCHAR(MAX), SET #step3Query = '...'
Then call this query in appropriated places by call "EXEC sp_executesql #step3Query". But I got a lot of errors, and I am not sure that is a correct way to do task like that.
Any suggestions would be highly appreciated.
Here is one method that could work (depending on your exact circumstance). The main thing for this is that it's easy, as well as easy to read.
You could have 3 variables to use as flags e.g., #Query3_Flag, #Query4_flag, #Query5_flag.
Your conditional checks just set these flags e.g.,
IF (condition1)
BEGIN
SET #Query4_Flag = 1;
SET #Query3_flag = 1;
SET #Query5_flag = 0;
END
Before each of queries 3, 4 and 5, have the IF statement check the flag and only run the query if the flag is set to 1 e.g.,
IF #Query3_Flag = 1
BEGIN
(run Query 3)
END
Note that the queries will need to be in the correct order.

use execSQL or COMMIT to conclude a transaction

What would be the right way to conclude a transaction ? :
Query.SQL.Add('START TRANSACTION;');
-----
-----
Query.SQL.Add('COMMIT;');
Query.ExecSQL;
or
Query.SQL.Add('START TRANSACTION;');
-----
-----
Query.ExecSQL;
Query.SQL.Add('COMMIT;');
edit :
Or this way :
.......
.......
try
if not Database1.InTransaction then
Database1.StartTransaction;
Query.ExecSQL;
Database1.Commit;
except on E : Exception do begin
Database1.Rollback;
Normally you have to control the transaction under try except to prevent errors from insert or update statements.. so I suggest
to use start transaction on tConnection and not on tquery under try except
try
AdoConnection1.BeginTrans;
----
----
query1.ExecSql;
AdoConnection1.CommitTrans;
except
AdoConnection1.RollbackTrans;
-----
// manage the exception after rollback
-----
end;
Note:
It's very important to place RollbackTrans at the first line in the exception management, because any other code as showmessage or anything else could lock a part of database tables for other users

SQLCMD - SQL Server Job

suppose below is my query.
DECLARE #INT INT
SET #INT = (SELECT COUNT(1) FROM MyTable)
IF (#INT = 0)
RAISERROR('Fail',16,1)
I want to use this query and create a SQL Server job using "Operating System (CmdExec)" type.
I want to SQL Job step to be successful if #INT <> 0 and fail if #INT = 0.
How can I write the cmd?
My try (and it doesn't work)...the server is different than where I will be setting up the job.
sqlcmd -S 123.45.67.890 -E -V15 -d MyDB -Q "DECLARE #INT INT
SET #INT = (SELECT COUNT(1) FROM MyTable)
IF (#INT = 0)
RAISERROR('Fail',16,1)" -b
Job failure msg.
Executed as user: LocalSVR\USER. Msg 105, Level 15, State 1, Server RemoteSVR, Line 1 Unclosed quotation mark after the character string 'DECLARE #INT INT '. Process Exit Code 15. The step failed.
Please note, the step fails for the same reason when MyTable has 1+ record(s).
Update: As per Scott's suggestion, I changed the formatting (removed line breaks) and it seems to work. #Scott, not sure how to mark your comment as answer. If you can write a response, I will mark it as answer. Cheers!!!
You're trying to execute multiple lines as opposed to a single query. You can get round that by using IF NOT EXISTS
SQLCMD -b -S"MyServer" -d"MyDatabase" -Q"IF NOT EXISTS(SELECT * FROM MyTable) RAISERROR('Fail',16,1)"
Note that the -b (On error batch abort) option means that SQLCMD itself will fail giving you a Trappable ErrorLevel

Command line script to delete Oracle records based on a column value

I am completely new to scripting techniques.
My requirement is
To connect oracle through DOS script
Based on a column value need to delete the particular record
eg:
emp sal pt_dt
a 23 22-02-11
b 34 20-01-10
c 45 23-09-85
d 56 30-3-11
Based on the 30-3-11(pt_dt column), I need to delete the record d.
OS - Windows XP
DB - Oracle 10g
Simplest method is to first write your sql (e.g. deleterec.sql) script, then call it from a batch (e.g. deleterec.bat) script.
Example contents of deleterec.sql:
DELETE emp WHERE pt_dt = TO_DATE('30-03-2011','DD-MM-RRRR');
Example contents of deleterec.bat:
sqlplus.exe scott/tiger#orcl #deleterec.sql
(replace scott/tiger#orcl with your user name, password and database instance)
You can write a .bat like this:
#echo off
if %%1X==X goto noparam
echo DELETE FROM emp e WHERE e.emp = '%%1' > deleterec.sql
sqlplus.exe scott/tiger#orcl #deleterec.sql
delete deleterec.sql
goto end
:noparam
echo Usage: %%0 {employee id}
goto end
:end
echo Bye!
I admit I stole the sqlplus call from Jeffrey's answer. :-o

Returning Errors without a stored procedure

I need to know the number of rows in a certain table. If it is under 250 rows I need to return an error to the sql job forcing it to quit. The problem is it's not a stored procedure. It's sql code is running straight from the job step as a Transact-SQL script. Is this possible to return anything, or is there a better way to do this?
This is what I have:
select case when (select cnt = count([col]) from db.dbo.table) < 250 THEN 1 ELSE 0 END
You can use the RAISERROR command.
IF (SELECT COUNT([col] FROM db.dbo.table) < 250
RAISERROR('My error message', 15, 1)
The severity level 15 is a level that will indicate to the job that the command failed.
Look here for more about the RAISERROR command.