How to validate SQL scripts
Hi,
How to Validate SQL scripts?
I am having set of sql files i wish to run one by one if there is any error at one file i need to notify to the user.I have created Bat file in-order to execute in a sequence.how to validate in bat file
say
01.sql ---Sucess
02.sql --- Fail -- intimate and not to execute rest of sql files
03.sql
04.sql
Thanks!
933663 wrote:
I am going to create the database
cloneDBCreation.sql
CloneRmanRestore.sql
init.ora
initEDIDBTemp.ora
lockAccount.sql
postDBCreation.sql
postScripts.sql
rmanRestoreDatafiles.sql
dbname.bat
dbname.sqlSo i need to validate each and every .sql whether it succeed or not. if there is failure then needs to notify the user. Use the SQL*Plus macro/command, WHENEVER SQLERROR EXIT <n>, to terminate a sql script when it hits an error - and have it return a specific exit code to the caller (o/s command line in this case). Note that exit codes are typically defined as a single byte in shells - which means it can only returns 0 to 255.
In the command line shell, check the exit code of the previous command - which would be command than ran sqlplus and the sql script. If the exit code is for example 255, then you know the WHENEVER SQLERROR command was executed. And then you cease processing sql scripts.
Simplistically (I do not do Windows), it will look as follows:
--// sql script
whenever sqlerror exit 255
... rest of the script
@echo off
rem command shell script
prompt executing script 1
sqlplus -s /nolog @sqlscript1.sql
if ERRORLEVEL 255 goto :ScriptFailed
prompt executing script 2
sqlplus -s /nolog @sqlscript2.sql
if ERRORLEVEL 255 goto :ScriptFailed
goto :Success
:ScriptFailed
echo ...
goto :End
:Sucess
echo ..
goto :End
:End
Similar Messages
-
How to call SQL Script in DBMS_SCHEDULER
How to call SQL Scripts in DBMS_SCHEDULER?
Things I got working
1) Successfully created and tested a PL/SQL that was created under SQL Workshop->SQL Scripts (I named it 'TEST'). I was able to run this no problem.
2) Successfully created a DBMS_SCHEDULER that runs every minutes. (See below)
begin
dbms_scheduler.create_job(
job_name => 'myjob',
job_type => 'plsql_block',
job_action => 'null;',
start_date => '19-JUL-11 03.10.00 PM', /* Remember to use the DB time, not your local time if not specifying a timezone */
repeat_interval => 'freq=minutely',
enabled => true);
end;The problem i am having is to make the PL/SQL script (named 'TEST') runs every minute. Its probably very easy to do that but i dont seems like finding any examples online.
I tried replacing the job_action attribute to " job_action => 'begin TEST; END;', " However, that did not work.
I am stuck here for couple hours already, any clues would be great :)
Thanks in advance
John
Application Express 4.1.0.00.32
Edited by: John Lau on Aug 14, 2012 12:47 PM
Edited by: John Lau on Aug 14, 2012 12:48 PMThe PL/SQL is pretty long, I would like to call it from a different location rather then putting the whole coding as part of the argument. Sounds like I should be looking into procedure package in database?
I will do some more research on procedure package, how to create one and how to call from it.
Thanks
John -
How to execute sql scripts from Powershell across multiple databases
Re: How to execute sql scripts from Powershell across multiple databases
I have an tsql script that I want to run across a list of databases. How is the best way to do this in Powershell? Thanks.My example below, using just the SMO and not breaking up the batches, the ExecuteWithResults give the following error when the .sql file contains a GO. My script files are as simple as a DECLARE and then a GO.
WARNING: SQL Script Failed
The object of type "Microsoft.PowerShell.Commands.Internal.Format.FormatStartData" is not valid or not in the correct sequence. This is likely caused by a user-specified "format-list" comm
and which is conflicting with the default formatting.
+ CategoryInfo : InvalidData: (:) [out-lineoutput], InvalidOperationException
+ FullyQualifiedErrorId : ConsoleLineOutputOutOfSequencePacket,Microsoft.PowerShell.Commands.OutLineOutputCommand
Also, when executing from the ISE, is there a way to force the ISE to release the files. I am having to close the ISE and reopen my script every time I want to make a testing change to the .sql file.
[reflection.assembly]::LoadWithPartialName("Microsoft.SqlServer.Smo")
$scriptspath = "C:\temp\psExecuteSQLScripts\scripts"
$SQLServer = "fidevc10"
$SQLDB = "Bank03"
# Create SMO Server Object
$Server = New-Object ('Microsoft.SQLServer.Management.Smo.Server') $SQLServer
# Get SMO DB Object
$db = $Server.Databases[$SQLDB]
# Load All SQL Scripts in Directory
$scripts = Get-ChildItem -Path (Join-Path $scriptspath "*") -Include "*.sql" -Recurse
# Loop through each script and execute
foreach ($SQLScript in $scripts)
$fullpath = $SQLScript.FullName
# Read the Script File into Powershell Memory
$reader = New-Object System.IO.StreamReader($fullpath)
$script = $reader.ReadToEnd()
# Execute SQL
Write-Host "Executing $SQLScript on $SQLDB...."
try
$ds = $db.ExecuteWithResults($script)
Foreach ($t in $ds.Tables)
Foreach ($r in $t.Rows)
Foreach ($c in $t.Columns)
Write-Host $c.ColumnName "=" $r.Item($c)
Write-Host "Complete"
catch [Exception]
Write-Warning "SQL Script Failed"
echo $_.Exception|format-list -force
Write-Host " " -BackgroundColor DarkCyan -
How to move SQL scripts using HANA ALM ?
I see clear documentation of moving the content easily from Dev to test and to production using DU which exports only content. Similarly can we use the transport management/ALM for moving sql scripts, for example table creation scripts or table structures that needs to be moved from Dev to QA ?
Thanks
SureshSutirtha,
Thank you very much. I really appreciate all of your responses.
I have one more question ( Sorry for flooding you with lot of questions :) )
How to capture the errors which occured inside the SQL Scripts.
My scenario is like this. I have two sql scripts Script_1.sql and Script2.sql namely. I would like to put dependency on the execution of the scripts.
If Script_1.sql executes succesfully without any errors, then EXECUTE Script_2.sql
else if Script_1.sql execution contains errors then DON'T EXECUTE Script_2.sql
As of now, i observed that the Process flow shows Success State even if there is an error in the sql script execution. Because of which i was not able to put dependency on the execution of the scripts.
I think i can do it by tweaking(changing) the code inside the SQL Scripts, like logging the errors in some log table and reading it before the next script execution.
But the restriction is, I Should not touch/change the existing SQL Scripts.
Do we have any mechanism in the ProcessFlows to identify the SQL Errors that occurred during execution of SQL Scripts ?
Please suggest any idea on this. It will be great if you can help in this.
Thanks in advance,
SriGP. -
How to execute SQL scripts using OWB Process flows ?
Hi,
I have some SQL Scripts. I have to execute them using OWB Process flows.
Can i get any document or link which helps me in achieving this?
Thanks in Advance,
SriGPSutirtha,
Thank you very much. I really appreciate all of your responses.
I have one more question ( Sorry for flooding you with lot of questions :) )
How to capture the errors which occured inside the SQL Scripts.
My scenario is like this. I have two sql scripts Script_1.sql and Script2.sql namely. I would like to put dependency on the execution of the scripts.
If Script_1.sql executes succesfully without any errors, then EXECUTE Script_2.sql
else if Script_1.sql execution contains errors then DON'T EXECUTE Script_2.sql
As of now, i observed that the Process flow shows Success State even if there is an error in the sql script execution. Because of which i was not able to put dependency on the execution of the scripts.
I think i can do it by tweaking(changing) the code inside the SQL Scripts, like logging the errors in some log table and reading it before the next script execution.
But the restriction is, I Should not touch/change the existing SQL Scripts.
Do we have any mechanism in the ProcessFlows to identify the SQL Errors that occurred during execution of SQL Scripts ?
Please suggest any idea on this. It will be great if you can help in this.
Thanks in advance,
SriGP. -
How to execute SQL Script using windows powershell(using invoke-sqlcmd or any if)
OS : Windows server 2008
SQL Server : SQL Server 2012
Script: Test.sql (T-SQL) example : "select name from sys.databases"
Batch script: windows MyBatchscript.bat ( here connects to sql server using sqlcmd and output c:\Testput.txt)
(sqlcmd.exe -S DBserverName -U username -P p@ssword -i C:\test.sql -o "c:\Testoutput.txt) ---it working without any issues.....
This can execute if i double click MyBatchscript.bat file and can see the output in c:\testput.txt.
Powershell: Similarly, How can i do in powershell 2.0 or higher versions? can any one give full details with each step?
I found some of them online, but nowhere seen clear details or examples and it not executing through cmd line (or batch script).
example: invoke-sqlcmd -Servernameinstance Servername -inputfile "c:\test.sql" | out-File -filepath "c:\psOutput.txt" --(call this file name MyTest.ps1)
(The above script working if i run manually. I want to run automatic like double click (or schedule with 3rd party tool/scheduler ) in Batch file and see the output in C drive(c:\psOutput.txt))
Can anyone Powershell experts give/suggest full details/steps for this. How to proceed? Is there any configurations required to run automatic?
Thanks in advance.Testeted the following code and it's working.....thanks all.
Execute sql script using invoke-sqlcmd with batch script and without batch script.
Option1: using Import sqlps
1.Save sql script as "C:\scripts\Test.sql" script in side Test.sql: select name from sys.databases
2.Save Batch script as "C:\scripts\MyTest.bat" Script inside Batch script:
powershell.exe C:\scripts\mypowershell.ps1
3.Save powershell script as "C:\scripts\mypowershell.ps1"
import-module "sqlps" -DisableNameChecking
invoke-sqlcmd -Servername ServerName -inputFile "C:\scripts\Test.sql" | out-File -filepath "C:\scripts\TestOutput.txt"
4.Run the Batch script commandline or double click then can able to see the output "C:\scripts\TestOutput.txt" file.
5.Connect to current scripts location cd C:\scripts (enter)
C:\scripts\dir (enter )
C:\scripts\MyTest.bat (enter)
Note: can able to see the output in "C:\scripts" location as file name "TestOutput.txt".
Option2: Otherway, import sqlps and execution
1.Save sql script as "C:\scripts\Test.sql" script in side Test.sql: select name from sys.databases
2.Save powershell script as "C:\scripts\mypowershell.ps1"
# import-module "sqlps" -DisableNameChecking #...Here it not required.
invoke-sqlcmd -Servername ServerName -inputFile "C:\scripts\Test.sql" | out-File -filepath "C:\scripts\TestOutput.txt"
3.Connect to current scripts location
cd C:\scripts (enter)
C:\scripts\dir (enter )
C:\scripts\powershell.exe sqlps C:\scripts\mypowershell.ps1 (enter)
Note: can able to see the output in "C:\scripts" location as file name "TestOutput.txt". -
How to call SQL script from PL/SQL block
Hi All,
I have a pl/sql block from which i need to call a *.sql script file.
Please tell me that how can i do this?
Thanks and Regards.> Though just for knowledge sake, would you please tell if there is a way
to call a sql script from a pl/sql block.
This question stems usually from a confusion about client-server and which is which in Oracle.
SQL*Plus is a client. PL/SQL is a server side language. SQL is a server side language.
When entering either one of these two languages in SQL*Plus (or TOAD, SQL-Developer, etc), the content is shipped to an Oracle server process, is parsed there, and is executed there.
The Oracle server process servicing the client can accept a single SQL statement or PL/SQL block at a time.
It cannot accept a block of SQL statements delimited with a semicolon. That is a client concept where the client will read each delimited statement and send that, one after the other (in synchronous call mode) to the Oracle server for execution.
The Oracle server does not have a "script parser". It understands SQL. It understands PL/SQL. And that is what it expects from the client.
Whether the client supports the SET command, the HOST command, SPOOL command, ability to run scripts, and so... have no bearing on what the server itself is capable of doing. The server does not care what feature set the client has. It is tasked with servicing the client via SQL and PL/SQL.
It is not tasked to support or emulate client features like running SQL scripts.
Nor confuse PL/SQL with the very limited command set of SQL*Plus. The two has nothing in common. And just as PL/SQL cannot understand C# or Delphi commands, it cannot understand SQL*Plus commands. -
Hi,
I am working on a perl script to test if the sql script file prepared by the Dev team can be deployed to the DB without any issue or not. My intention is not to run the script but only to check if the script will run properly without any error at the time of actual deploy or not. Is there a way wherein I can mimic the execution of the script?
consider, I has a script file CreateTable.sql which contains CREATE TABLE statement. I dont want the table to be created by mimic actual run of this script against the database. How do I do that?
TIA
-Onkaronkar.nath wrote:
I am working on a perl script to test if the sql script file prepared by the Dev team can be deployed to the DB without any issue or not. My intention is not to run the script but only to check if the script will run properly without any error at the time of actual deploy or not. Is there a way wherein I can mimic the execution of the script?
consider, I has a script file CreateTable.sql which contains CREATE TABLE statement. I dont want the table to be created by mimic actual run of this script against the database. How do I do that?Do that by being creative? ;-)
Not possible using PL/SQL. PL/SQL has a a very flexible DBMS_SQL cursor interface - that amongst other things allow you to parse a statement into a cursor. However, a parse call also automatically executes if the parsed cursor is a DDL. With DML, you can parse and not execute.
The only other way that comes to mind is using the EXPLAIN PLAN command in the SQL language. E.g.
SQL> explain plan
2 set statement_id = 'ddl.parse.1'
3 for create table testtab2 nologging as select * from user_objects;
Explained.
SQL> --//object not created
SQL> desc testtab2
ERROR:
ORA-04043: object testtab2 does not existThere could perhaps be a method using the OCI (Oracle Call Interface) to parse a DDL without executing it. Are you using Perl-DBI? In that case you may want to look at the OCI and how Perl-DBI exposes that - and whether a DDL can be parsed as cursor without executing it. -
How to load SQL scripts from a text file.
Hi, i tried several time to load a text file/SQL script with 10 different tables and data, but 10g Express doesen't allows me to do that, any one can direct me or point out to me what i should do or do i need to adopt any special method to to get this done. i am sure there must be some thing where you can upload SQL scripts from a text file (in SQL command editor!). thanks
Hi,
see my other answer here:
SQL command editor doesn't take more than 1 insert command
This seems to be a duplicate question, right? Or am I missing something?
Regards,
~Dietmar. -
How to get SQL script for generating table, constraint, indexes?
I'd like to get from somewhere Oracle tool for generating simple SQL script for generating table, indexes, constraint (like Toad) and it has to be Oracle tool but not Designer.
Can someone give me some edvice?
Thanks!
m.I'd like to get from somewhere Oracle tool for
generating simple SQL script for generating table,
indexes, constraint (like Toad) and it has to be
Oracle tool but not Designer.
SQL Developer is similar to Toad and is an Oracle tool.
http://www.oracle.com/technology/products/database/sql_developer/index.html -
How to generate sql script based on table structure
I want to generate a sql script based on a table structure.
For example:
if the table is:
cid id c_value
1 1 zz
2 1 yy
3 2 zz
4 2 xx
5 3 ss
6 3 tt
The expected output is:
WITH
CHILD_tab as (
SELECT 1 cid, 1 id,'zz' c_value from dual union all
SELECT 2 cid, 1 id,'yy' c_value from dual union all
SELECT 3 cid, 2 id,'zz' c_value from dual union all
SELECT 4 cid, 2 id,'xx' c_value from dual union all
SELECT 5 cid, 3 id,'ss' c_value from dual union all
SELECT 6 cid, 3 id,'tt' c_value from dual )
Release 11.1.0.7.0I'm doing a lot of XML these days (too much perhaps) so here's a solution involving XQuery.
We pass a query string and it outputs a CLOB containing the WITH clause :
SELECT DBMS_XMLGEN.Convert(
XMLQuery(
q'[concat(
"WITH t AS (
string-join(
for $i in /ROWSET/ROW
return concat( " SELECT ",
string-join($i/*/concat("'",ora:replace(text(),"'","''"),"' ",local-name()),", "),
" FROM dual" ),
" UNION ALL
passing dbms_xmlgen.getXMLType('SELECT * FROM scott.emp')
returning content
).getClobVal(), 1) AS WITH_CLAUSE
FROM dual;
WITH_CLAUSE
WITH t AS (
SELECT '7369' EMPNO, 'SMITH' ENAME, 'CLERK' JOB, '7902' MGR, '17/12/80' HIREDATE, '800' SAL, '20' DEPTNO FROM dual UNION ALL
SELECT '7499' EMPNO, 'ALLEN' ENAME, 'SALESMAN' JOB, '7698' MGR, '20/02/81' HIREDATE, '1600' SAL, '300' COMM, '30' DEPTNO FROM dual UNION ALL
SELECT '7521' EMPNO, 'WARD' ENAME, 'SALESMAN' JOB, '7698' MGR, '22/02/81' HIREDATE, '1250' SAL, '500' COMM, '30' DEPTNO FROM dual UNION ALL
SELECT '7566' EMPNO, 'JONES' ENAME, 'MANAGER' JOB, '7839' MGR, '02/04/81' HIREDATE, '2975' SAL, '20' DEPTNO FROM dual UNION ALL
SELECT '7654' EMPNO, 'MARTIN' ENAME, 'SALESMAN' JOB, '7698' MGR, '28/09/81' HIREDATE, '1250' SAL, '1400' COMM, '30' DEPTNO FROM dual UNION ALL
SELECT '7698' EMPNO, 'BLAKE' ENAME, 'MANAGER' JOB, '7839' MGR, '01/05/81' HIREDATE, '2850' SAL, '30' DEPTNO FROM dual UNION ALL
SELECT '7782' EMPNO, 'CLARK' ENAME, 'MANAGER' JOB, '7839' MGR, '09/06/81' HIREDATE, '2450' SAL, '10' DEPTNO FROM dual UNION ALL
SELECT '7788' EMPNO, 'SCOTT' ENAME, 'ANALYST' JOB, '7566' MGR, '19/04/87' HIREDATE, '3000' SAL, '20' DEPTNO FROM dual UNION ALL
SELECT '7839' EMPNO, 'KING' ENAME, 'PRESIDENT' JOB, '17/11/81' HIREDATE, '5000' SAL, '10' DEPTNO FROM dual UNION ALL
SELECT '7844' EMPNO, 'TURNER' ENAME, 'SALESMAN' JOB, '7698' MGR, '08/09/81' HIREDATE, '1500' SAL, '0' COMM, '30' DEPTNO FROM dual UNION ALL
SELECT '7876' EMPNO, 'ADAMS' ENAME, 'CLERK' JOB, '7788' MGR, '23/05/87' HIREDATE, '1100' SAL, '20' DEPTNO FROM dual UNION ALL
SELECT '7900' EMPNO, 'JAMES' ENAME, 'CLERK' JOB, '7698' MGR, '03/12/81' HIREDATE, '950' SAL, '30' DEPTNO FROM dual UNION ALL
SELECT '7902' EMPNO, 'FORD' ENAME, 'ANALYST' JOB, '7566' MGR, '03/12/81' HIREDATE, '3000' SAL, '20' DEPTNO FROM dual UNION ALL
SELECT '7934' EMPNO, 'MILLER' ENAME, 'CLERK' JOB, '7782' MGR, '23/01/82' HIREDATE, '1300' SAL, '10' DEPTNO FROM dual
)It may be useful for small data sets only because we quickly hit ORA-01706. -
How to run sql scripts using batch file for a web dynpro data dictionary
Hi,
I want to develop a sql script to be executed on the server alongwith the installation of a product to pre-populate web dynpro data dictionary tables required for the application.
I further require to make the scripts independent of the database name,so that it can be run at any client environment.
Your help will be appreciated and rewarded.See shoblock's answer
call sql script from unix
masterfile.sql:
@file1 &1
@file2 &2
@file3 &3
@file4 &4
then just call the master script:
sqlplus userid/password @masterfile <p1> <p2> <p3> <p4> -
How to generate sql script of database user
hello, I would like to generate the SQL script definition of a database user using JDveloper IDE (from ide connection).
Best Regards.You want to use jdeveloper to extract the info, don't you. The tool mostly used here is sql*plus.
You won't get any responses.
Sybrand Bakker
Senior Oracle DBA -
How to execute SQL scripts in batch
Hi,
I have separate scripts for Creation of Tables, Stored Procedures, Views, Triggers in different .sql files.
I have to execute thses scripts in batch in different servers and different databases without opening SSMS.
All .sql files to be executed in single command.
Please suggest how to achieve?
Appreciate your help.
Regards,
Balayou can use sqlcmd
https://msdn.microsoft.com/en-us/library/ms162773.aspx
other options are osql,isql
https://technet.microsoft.com/en-us/library/aa214012%28v=sql.80%29.aspx
https://technet.microsoft.com/en-us/library/aa214007%28v=sql.80%29.aspx
Please Mark This As Answer if it solved your issue
Please Vote This As Helpful if it helps to solve your issue
Visakh
My Wiki User Page
My MSDN Page
My Personal Blog
My Facebook Page -
How to execute sql script from linux command line
Hello everyone !
Just short question. On my server I must install script in crontab which will eexecute some sql statements.
How can I write command which will execute script from file without asking about password ?
sqlplus user/pass ... and then what ?
thanks
dlugasxuser10064952 wrote:
Just short question. On my server I must install script in crontab which will eexecute some sql statements.
How can I write command which will execute script from file without asking about password ?Crontab does not run your local shell profile - which means no valid Oracle environment for SQL*Plus to execute in.
On newer cron versions, you can add an environment to the crontab file itself that needs to be set before executing the scheduled command.
Whatever method - make sure you have ORACLE_HOME set, that the path includes ORACLE_HOME/bin, that ORACLE_SID is set (if not using a TNS alias) and so on.
But I agree with Sybrand... crontab is not the best place for running SQL or PL/SQL code. That should reside in the database as named code (e.g. stored procs) and be executed via DBMS_JOB or DBMS_SCHEDULE.
Less moving parts that way. No external dependancies. And will work on any Oracle server, irrespective of the o/s used and whether or not the relevant o/s user has batch/cron/etc privs to do the deed.
Maybe you are looking for
-
I work for a publisher and we use InDesign to set up our print files to be uploaded (usually in PDF format). Then I create a new file for the ebooks, removing extra pages, marking the table of content entries as internal hyperlinks, etc. Since the Ki
-
Photoshop CS6 upgrade from CS4 continually asks for serial number.
I purchased an upgrade from Photoshop CS 4 to Photoshop CS 6 directly from Adobe in December of 2012. (My version of CS4 was originally purchased by me as part of a CS4 Web Premium Suite.) My CS4 version has worked since 2009 with no licensing issues
-
Downloading to an EXCEL SHEET from Std Transaction.
Hi All, I have requirement in FI in a transaction "FAGLL03" where in I want to download the data to an excel sheet, but there are records minimum of 8000 and when I am trying to download then it's going to DUMP saying timeout. Br, Laxmi.
-
This is a re=post of an earlier post that was removed by the moderators. I did the update and all appears fine. While its nice that they provided 5.0 for ATV2's I do hope they provide a way to organize the home screen. Now with the menu nesting gon
-
Please i want to call a HTTPService to populate markers from external .xml file instead of populating it directly in the main.mxml. Thank you! [Embed(source="image/cinemaMarker.png")] protected var MarkerImage:Class; private var srcXML:XML = <