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".
Similar Messages
-
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 execute SQL Query in Code behind Using infopath 2010?
Hi,
I've repeatable on infopath form, and want bind it throuth code behind from SQL table. My question is that how to execute SQL Query in code behind from infopath as well as how would get Query result to bind repeatable control?
Thanks In Advance
Shoeb AhmadHello,
You first need to add new SQL DB connection then you need execute connection from code behind.
See below link to create new connection
http://office.microsoft.com/en-in/infopath-help/add-a-data-connection-to-a-microsoft-sql-server-database-HP010092823.aspx:
http://www.bizsupportonline.net/infopath2010/connect-infopath-2010-sql-server-2008-table.htm
Then use below code to execute this connection:
AdoQueryConnection conn = (AdoQueryConnection)(this.DataConnections["Data connection name"]);
string origCommand = Select * from tablename;
conn.Command = origCommand;
conn.Execute();
Finally bind your table:
http://www.bizsupportonline.net/infopath2007/4-way-programmatically-add-row-repeating-table.htm
http://stevemannspath.blogspot.in/2010/09/infopath-20072010-populate-repeating.html
Hope it could help
Hemendra:Yesterday is just a memory,Tomorrow we may never see
Please remember to mark the replies as answers if they help and unmark them if they provide no help -
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 run SQL script file on Linux using Java ?
Hi,
I need to execute .sql file using java. I used following approach for this.
private void runScriptEvent(java.awt.event.ActionEvent evt) {
String sqlOutput = "";
String sqlPromptLines="";
String currentFunctionName = "";
if(con!=null){
String userName = jTextField4.getText();
String password = jPasswordField1.getText();
String databaseName = jTextField3.getText();
try {
String script_location = "";
ProcessBuilder processBuilder =null;
Process process = null;
//File file = new File("C:/ScriptFile");
File file = new File("./SQL_Script");
//File file = new File("E:\\install\\SQL_Script");
if(file.exists()){
File [] list_files= file.listFiles(new FileFilter() {
public boolean accept(File f) {
if (f.getName().toLowerCase().endsWith(".sql"))
return true;
return false;
int count = 0;
for (int i = 0; i<list_files.length;i++){
script_location = "@" + list_files.getAbsolutePath();//ORACLE
//currentFunctionName = list_files[i].getName();
StringTokenizer st = new StringTokenizer(list_files[i].getName(), ".");
while(st.hasMoreTokens()) {
currentFunctionName = st.nextToken();
String extention= st.nextToken();
System.out.println("Function Name = "+currentFunctionName + "\t Extention = " + extention);
processBuilder = new ProcessBuilder("sqlplus",userName+"/"+password+"@"+databaseName, script_location); //ORACLE
processBuilder.redirectErrorStream(true);
process = processBuilder.start();
BufferedReader in = new BufferedReader(new InputStreamReader(process.getInputStream()));
String currentLine = null;
while ((currentLine = in.readLine()) != null) {
sqlPromptLines = " "+sqlPromptLines + currentLine +"\n";
count ++;
System.out.println(count+" " + currentLine);
if(currentLine.equalsIgnoreCase("Function created.")){
sqlOutput = "\n" sqlOutput currentFunctionName + " " currentLine"\n" ;
break;
}// end while
in.close();
process.destroy();
}//end for
}//end if file exists
} catch (IOException e1) {
jTextArea1.setText(e1.getMessage());
System.out.println("Script Done");
jTextArea1.append(sqlOutput);
}// end id Connection is not null
Above code working appropriate on Windows but not on Linux.
is there any changes needed ?
Regards,
Ajay
Edited by: Ajay Sharma on Nov 21, 2012 6:43 PMHi gimbal2,
about code
jTextArea1.setText(e1.getMessage());I am using this code so that the user will be prompted with a message rather than stack trace.
About the issue I am getting on linux i believe its because of following statement.
processBuilder = new ProcessBuilder("sqlplus",userName+"/"+password+"@"+databaseName, script_location); //ORACLERegards,
Ajay
Edited by: Ajay Sharma on Nov 23, 2012 12:05 PM
Edited by: Ajay Sharma on Nov 23, 2012 12:06 PM -
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 files with windows path ?
Hi , here's my stupid question :
I have my parent SQL script say A.sql in directory C:\program files\my files\A.sql
A.sql has calls to multiple sql files like this
@@1.sql;
@@2.sql;
When I call A.sql using sqlplus as:
sqlplus <username> <connection_string> @"C:\program files\my files\A.sql"
A.sql gets executed but then while calling "1.sql" it fails with the error
SP2-0310: unable to open file "C:\program.sql"
This is happening because of the space, how can this be handled. thx in advance :)
Regards,
Neuronmy A.sql is:
@@1.sql
@@2.sql
1.sql and 2.sql are in the same directory as A.sql.
sqlplus <username> <connection_string> @"C:\program files\my files\A.sql"
VG2,
Yes. Specify the entire path/filename and put double quotes around itA.sql has the double quotes around it, however what additional things can be done so that 1.sql and 2.sql which are present in same directory as A.sql also runs.
Ashish,
Yes the assumption is correct. Although when I cd to this directory then this issue won't come for sure.
But the requirement is you can't 'cd' to the directory and want to execute with complete path.
There is no issues in Solaris as the space is not allowed. -
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. -
How to execute SQL scripts with MaxDB ..?
Hi all,
i got some clue from another thread and i observed the command is like
sqlcli -d DBNAME -u SQLUSER,SQLPASS -i filename.sql -c <delimiter> is there,
when i use this the only first query is successfully executing,
this might be problem with delimiter.
can any body help how to use delimiter in the script file with an example.
thanks in advance.
--HariHi,
Sample Script
CREATE TABLE city
(zip CHAR (5) KEY CONSTRAINT zip BETWEEN '10000' AND '99999',
name CHAR(20) NOT NULL,
state CHAR(2) NOT NULL)
CREATE TABLE customer
(cno FIXED (4) KEY CONSTRAINT cno BETWEEN 1 AND 9999,
title CHAR (7) CONSTRAINT title IN ('Mr', 'Mrs', 'Company'),
firstname CHAR (10) ,
name CHAR (10) NOT NULL,
zip CHAR (5) CONSTRAINT zip BETWEEN '10000' AND '99999',
address CHAR (25) NOT NULL,
FOREIGN KEY (zip) REFERENCES city ON DELETE RESTRICT)
\dt customer
COMMIT
Regards
Ayyapparaj -
Windows PowerShell is a powerful command tool and we can use it for management and operations. In this article we introduce the detailed steps to use Windows PowerShell to find and replace test string in the
shapes in Excel Object.
Since the Excel.Application
is available for representing the entire Microsoft Excel application, we can invoke the relevant Properties and Methods to help us to
interact with Excel document.
The figure below is an excel file:
Figure 1.
You can use the PowerShell script below to list the text in the shapes and replace the text string to “text”:
$text = “text1”,”text2”,”text3”,”text3”
$Excel
= New-Object -ComObject Excel.Application
$Excel.visible = $true
$Workbook
= $Excel.workbooks.open("d:\shape.xlsx")
#Open the excel file
$Worksheet
= $Workbook.Worksheets.Item("shapes")
#Open the worksheet named "shapes"
$shape = $Worksheet.Shapes
# Get all the shapes
$i=0
# This number is used to replace the text in sequence as the variable “$text”
Foreach ($sh in $shape){
$sh.TextFrame.Characters().text
# Get the textbox in the shape
$sh.TextFrame.Characters().text =
$text[$i++]
#Change the value of the textbox in the shape one by one
$WorkBook.Save()
#Save workbook in excel
$WorkBook.Close()
#Close workbook in excel
[void]$excel.quit()
#Quit Excel
Before invoking the methods and properties, we can use the cmdlet “Get-Member” to list the available methods.
Besides, we can also find the documents about these methods and properties in MSDN:
Workbook.Worksheets Property (Excel):
http://msdn.microsoft.com/en-us/library/office/ff835542(v=office.15).aspx
Worksheet.Shapes Property:
http://msdn.microsoft.com/en-us/library/office/ff821817(v=office.15).aspx
Shape.TextFrame Property:
http://msdn.microsoft.com/en-us/library/office/ff839162(v=office.15).aspx
TextFrame.Characters Method (Excel):
http://msdn.microsoft.com/en-us/library/office/ff195027(v=office.15).aspx
Characters.Text Property (Excel):
http://msdn.microsoft.com/en-us/library/office/ff838596(v=office.15).aspx
After running the script above, we can see the changes in the figure below:
Figure 2.
Please click to vote if the post helps you. This can be beneficial to other community members reading the thread.Thank you for the information, but does this thread really need to be stuck to the top of the forum?
If there must be a sticky, I'd rather see a link to a page on the wiki that has links to all of these ForumFAQ posts.
EDIT: I see this is no longer stuck to the top of the forum, thank you.
Don't retire TechNet! -
(Don't give up yet - 13,085+ strong and growing) -
Hi All,
I am very new user of Oracle JDeveloper and BPEL. I am trying to develop a process flow in JDeveloper using BPEL and get stuck when I was trying to execute a SQL quiry in the flow.
How to execute SQL quiries using JDeveloper and BPEL?????????????
Possibilities might be..
1.Configring Database Adapter
2.Using Java Embedded activities of BPEL
However, any of the above mentioned way is not clear with me how to implement it to get the query run in the process flow.
It will be great if anyone could help me with this concept....
Thanks in advance
-Prabha
Edited by: user10259700 on Sep 15, 2008 3:48 AMHi,
though BPEL has its development environment in JDeveloper, it has its own forum
BPEL
Frank -
How to execute SQL Quiries in BPEL using JDeveloper
Hi All,
I am very new user of Oracle JDeveloper and BPEL. I am trying to develop a process flow in JDeveloper using BPEL and get stuck when I was trying to execute a SQL quiry in the flow.
How to execute SQL quiries using JDeveloper and BPEL?????????????
Possibilities might be..
1.Configring Database Adapter
2.Using Java Embedded activities of BPEL
However, any of the above mentioned way is not clear with me how to implement it to get the query run in the process flow.
It will be great if anyone could hepl me with this concept....
Thanks in advance
-Prabha... or perhaps just scan the last 5 posts before you post a new thread, in which case, you'd discover that someone else already asked Help needed in executing SQL query... and got the same answer
-
How to execute sql-queries through shell scripting in linux?
How to execute sql-queries through shell scripting in linux?
http://www.oracle.com/technology/pub/articles/saternos_scripting.html
Two simple examples:
#!/usr/bin/env bash
set_orafra () {
orafra=`echo 'set heading off
select name from v$recovery_file_dest;
exit' | sqlplus -s / as sysdba`
set_orafra
echo $orafra
#!/usr/bin/env bash
export ORACLE_SID=instance_name
export ORACLE_HOME=/path_to_oracle_home_directory
export LD_LIBRARY_PATH=$ORACLE_HOME/lib
export PATH=/$ORACLE_HOME/bin/$PATH
$ORACLE_HOME/bin/sqlplus -s <<EOF
connect scott/tiger@my_instance_name
INSERT INTO table VALUES (sysdate);
exit
EOFEdited by: Markus Waldorf on Sep 17, 2010 12:19 AM -
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 -
How to execute sql qurery in st05
how to execute sql qurery in st05
thanks in advanced.Hi,
do this....
1.create a small ABAP/4 program that contains only the select statement. Before proceeding, test it to ensure that it works.
2.Open that program in the editor so that it is ready and waiting to execute.
3.Open a new session using the menu path System->Create session.
4.Run transaction ST05 (enter /nst05-zero-five, not oh-five-in the Command field, or choose the menu path System->Utilities->SQL Trace). The Trace SQL Database Requests screen is displayed.
5.If the Trace SQL Status Information box reads Trace SQL is switched off, go to step 7.
6.At this point, the Trace SQL Status Information box contains Trace SQL switched on by, followed by the user id who turned on the trace and the date and time it was started. You must switch it off before you can proceed. If the trace was started within the past hour, it is possible that it is still being used. Contact the indicated user or try again later. If the trace was started hours or days ago, the user probably left it on by mistake and it can be safely turned off. To turn off the trace, press the Trace Off pushbutton. The message in the Trace SQL Status Information box should now read Trace SQL is switched off.
7.Press the Trace On pushbutton. The Trace SQL Database Requests dialog box is displayed. The DB-Trace for User field should contain your user ID. If your user ID is not in this field, enter it now.
8.Press the OK button. You are returned to the Trace SQL Database Requests screen and the status information reads Trace SQL switched on by, indicating that you turned on the trace.
9.Switch back to the window containing your editor session (the one with your program waiting to execute).
10.Press F8 to run your program. (Only press F8, do not do anything else, do not even press the Back button.)
11.When your program has run and the hourglass is no longer displayed, switch back to the trace window.
12.Press the Trace Off pushbutton. The status information reads Trace SQL is switched off.
13.Press the List Trace pushbutton. The Trace SQL Database Requests dialog box is displayed. The fields on this screen will already contain values.
14.Press the OK button. You might need to wait a little while, at most a couple of minutes. The Trace SQL: List Database Requests screen is displayed.
15.Type %sc in the Command field and press the Enter key. The Find dialog box is displayed.
16.Type the name of the table you are tracing in the Search For field. (This is the table named in the select statement in your ABAP/4 program.)
17.Press the Find button. A search results list should be displayed with your table name highlighted.
18.Click on the first highlighted table name. You are returned to the Trace SQL: List Database Requests screen. Your cursor is positioned on the first line containing your table name. To the right of it, in the Operation column, should be the word PREPARE, OPEN, or REOPEN.
19.Press the Explain SQL button on the Application toolbar. The Show Execution Plan for SQL Statement screen is displayed.
20.Scroll down to the execution plan. The index used will be displayed in blue.
Maybe you are looking for
-
Help creating a date of birth form in Acrobat 9 standart
I am using Acrobat 9 standard so I don't have LiveCycle. I am trying to create a birth date field in my questionnaire for new students. I am stuck. Does anyone know how to help me? I am new to this so I am not sure what I am doing.
-
Hi. I have a new Panasonic Viera smart tv and a Humax 1000s, both linked to my BT home hub 3 via Ethernet cables. They both operate fine via the internet and I can see their mac addresses on the router info when I interrogate it - all ticketyboo. I t
-
Acrobat 11what to do with the f character.
Hello all: I am parsing text from a PDF using the Acrobat Javascript API. The code looks like this for(var a = 0; a < PageCount; a++) for(var b = 0; b < NumWords; b++) var TheWord = this.getPageNthWord(a, b, false); The problem with this
-
Has anyone heard when Google Map's Street View will be supported??
I thought it might be included with the recent update but that just got me iTunes...
-
REDUCE THE BACKUP TIME/RMAN
I am taking full backup every week end. But its taking a long time to complete as size of database is very big. Is ther any way to do backup fastly as parrallal processing . We are using RMAN. Kindly tell me some way.