How to execute a .SQL script file?

Hi
I'm sure this question has been answered already, however I was unable to find an answer using the search tool.
Using c# I'd like to run a .sql file. The sql file contains multiple sql statements, some of which are broken over multiple lines. I tried reading in the file and tried executing the file using ODP.NET ... however I don't think ExecuteNonQuery is really designed to do this.
So I tried using sqlplus via spawning a process ... however unless I spawned the process with UseShellExecute set to true sqlplus would hang and never exit. Here's the code that DOESN'T WORK.
Process p = new Process();
p.StartInfo.UseShellExecute = false;
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.FileName = "sqlplus";
p.StartInfo.Arguments = string.Format("xx/xx@{0} @{1}", in_database, s);
p.StartInfo.CreateNoWindow = true;
bool started = p.Start();
p.WaitForExit();
WaitForExit never returns .... Unless I set UseShellExecute to true. A side effect of UseShellExecute is that you can no capture the redirected output.
This must be such a common thing to do, I'm hoping someone has a solution to this.
Thanks
Rich

If by "SQL script" you mean run a program that resides outside the database (a file of the format whatever.sql) then the answer is with difficulty. We can use extproc calls to run c libraries or embedded java to execute host-style commands but it's a lot of pfaffing about.
The easiest solution is to bring the SQL commands into the database as a stored procedure. If you still need to be able to run the script externally then rewrite that to call the same stored procedure. However, if the .SQL file includes OS calls then you will have to choose either Java or extproc, depending on what it is the script actuually does. If you want more focused advice you'll need to give us details.
Cheers, APC

Similar Messages

  • How to execute a sql script in dbms_job?

    how to execute a sql script in dbms_job?

    See my response to Re: how to execute a sql script file in procedure or trigger.
    Cheers, APC

  • How to execute power shell script file inside DSC script resource

    Hi,
    How to execute /call powershell scirpt file inside DSC script resource , some thing like below and capture the status of execution.
    Node $AllNodes.NodeName
    Script ExecuteSQLDeploy
    #SetScript = {powershell.exe .\SQLDeploy.ps1  "param1" "param2" "param3" "param4" "param5" }
    #TestScript= {powershell.exe .\SQLDeploy.ps1  "param1" "param2" "param3" "param4" "param5 }
    #GetScript= { return $true;}
    Basawaraj

    Thanks for reply. 
     Now i am able to execute the power shell script with DSC. I  am getting no error when i run , but the script logic wrote inside  ( deploying sql incremental changes ) not working . I am using SQLCMD in the powershell script to deploy sql
    changes . Can you please elaborate on "script is compatible with DSC" , the script
    should not contain write-host cmdlet.... etc something like that.
    Copying recursively from ****************************** to ************************** succeeded.
    Perform operation 'Invoke CimMethod' with following parameters, ''methodName' = SendConfigurationApply,'className' = MSFT_DSCLocalConfigurationManager,'namespaceName' = root/Microsoft/Windows/DesiredStateConfiguration'.
    An LCM method call arrived from computer ************ with user sid **********************************************
    [V-BAKANT]: LCM:  [ Start  Set      ]
    [V-BAKANT]: LCM:  [ Start  Resource ]  [[Script]ExecuteSQLDeploy]
    [V-BAKANT]: LCM:  [ Start  Test     ]  [[Script]ExecuteSQLDeploy]
    [V-BAKANT]: LCM:  [ End    Test     ]  [[Script]ExecuteSQLDeploy]  in 0.1110 seconds.
    [V-BAKANT]: LCM:  [ Start  Set      ]  [[Script]ExecuteSQLDeploy]
    [V-BAKANT]: LCM:  [ End    Set      ]  [[Script]ExecuteSQLDeploy]  in 0.3010 seconds.
    [V-BAKANT]: LCM:  [ End    Resource ]  [[Script]ExecuteSQLDeploy]
    [V-BAKANT]: LCM:  [ End    Set      ]
    [V-BAKANT]: LCM:  [ End    Set      ]    in  0.8810 seconds.
    Operation 'Invoke CimMethod' complete.
    Time taken for configuration job to complete is 0.923 seconds
    Basawaraj

  • How to execute a  .sql file from a batch file

    Hi all
    I've to take backup of a database weekly twice on every wednesday & Friday @ 5pm IST. I've written a hot backup script, which works every well.
    now i want to automate the script. ie i want this script to run on wednesday & friday @ 5pm without any human interfearance ie with out actually any1 executing this script.
    i created a batch file prod.bak with the following lines
    @echo off
    set oracle_sid=testdb
    set oracle_home=d:\oracle\ora92
    sqlplus /nolog
    connect sys as sysdba/oracletest@testdb
    this batch file when eexecuted connects me to sql prompt.
    Now i want to execute my backup script bkp.sql automatically when it is connected to sql prompt.
    (i tried with these lines in the above batch file...
    call bkp.sql---it just opens the bkp.sql file in notepad & displays the script
    start bkp.sql---same as call
    connect / as sysdba/pwd@[email protected] --- does not work simply remains a the sql prompt.
    At 17:00 /Every:w,f "d:\bkp.sql"---does not work simply remains at the sql promt.)
    Can any1 let me know what should i write in the batch file that will execute the bkp.sql file automatically after it gets connected to sql prompt. M using oracle 9i.
    I'll manage he time through windows utility of scheduling task.. Let me know how to execute the .sql file from a batch file.
    Thanks
    Tripti

    Try
    sqlplus "sys/oracletest as sysdba" @bpk.sql
    Working locally, and having set the ORACLE_SID, you don't need to specify the SqlNet alias (@testdb).
    Remember to put an exit at the end of the bpk.sql script.

  • How can I run a SQL script file...

    How can I run a SQL script file from a location on my computer without providing the whole path?
    Is there some way I can set a "Working folder" in SQL Plus??
    Thanks!
    Tom

    You can create an environment variable called "SQLPATH" which is a list of directories that SQL*Plus will search for your .SQL
    scripts.
    I would like to use another directory than the oracle/bin...
    How can I do this ??
    Hello,
    U can do this by this way:
    Save odm_script.sql file to the default Oracle
    directory i.e. Oracle-Home/bin and Run following command
    through SQL Plus.
    SQL>@Script_Name
    I hope this will resolve ur problem.
    Regards,
    Omer Saeed Khan.

  • How to execute a sql file inside a plsql file?

    It's easy to exec a plsql inside a sql. Simply
    start my_proc.plsql
    exec my_proc;
    But how to execute a sql file inside a plsql file?
    declare ...
    begin
    start my_sql.sql?
    end;
    Thanks.
    - Zac

    Doesn't work. Even though @ is different from start in this case but it just doesn't like the way sql and plsql are mixed. For example:
    DECLARE n NUMBER := 0;
    BEGIN
    select COUNT(*) INTO n from user_tab_partitions;
    DBMS_OUTPUT.put_line('Number of partitioned tables = ' || to_char(n));
    if n = 0 then
    DBMS_OUTPUT.put_line('createViewsProcs.sql');
    @createViewsProcs.sql
    else
    DBMS_OUTPUT.put_line('createPartitionViewsProcs.sql');
    @createPartitionViewsProcs.sql
    end of;
    END;
    SQL> @postimp.sql
    SQL> DECLARE n NUMBER := 0;
    2 BEGIN
    3 select COUNT(*) INTO n from user_tab_partitions;
    4
    5 DBMS_OUTPUT.put_line('Number of partitioned tables = ' || to_char(n));
    6
    7 if n = 0 then
    8 DBMS_OUTPUT.put_line('createViewsProcs.sql');
    9 @createViewsProcs.sql
    9 SET SERVEROUTPUT ON SIZE UNLIMITED;
    10 SET TERM ON;
    11 SET ECHO ON;
    12 EXEC DBMS_OUTPUT.put_line('STARTING VIEWS, PROCS, ETC, THIS MAY TAKE A FEW MINUTES');
    13 EXEC DBMS_OUTPUT.put_line(SYSTIMESTAMP());
    14
    15
    16 CREATE OR REPLACE PACKAGE db_convert AS
    17 FUNCTION ......
    32 END;
    33 /
    SET SERVEROUTPUT ON SIZE UNLIMITED;
    ERROR at line 9:
    ORA-06550: line 9, column 5:
    PL/SQL: ORA-00922: missing or invalid option
    ...

  • Execute an SQL Script from Java (myScript.sql) ?

    Hello!
    I am a writing an SQL Script so that I can re-create my database on another server (im using my laptop to test it on first though).
    I'm connecting to mySQL server using JDBC which works fine, but I was wondering
    how can I run an entire script file, say myScript.sql from within a Java class??
    (an SQL Script is simply a file containing the regular SQL commands and expressions that you might enter at an sql command line prompt)
    example of an SQL Scritp: myScript.sql>>
    //#create new db
    CREATE DATABASE sample_db;
    //#set active db
    USE sample_db;
    //#set table paramaters
    CREATE TABLE monkeys
    (name CHAR(20),
      age INT UNSIGNED,
      sex ENUM('M','F')
    //#create standard monkeys
    INSERT INTO monkeys(name,age,sex) VALUES("Sammy",10,"M");
    INSERT INTO monkeys(name,age,sex) VALUES("Muncht",12,"M");
    INSERT INTO monkeys(name,age,sex) VALUES("Jill",8,"F");
    //#get recordset
    SELECT * FROM monkeys WHERE age < 50;Thanks for your help!

    The way I understand it is that your mysql.sql script file uses ';' as a delimeter between statements. So now what you can do is that read the whole file and put it inside a string/stringbuffer. Now put this string/stringbuffer to a stringTokenizer with delimeter set as ';'. this way you will recieve your exact statements without scratching your heads as where the statements begin/ends. :-)
    Now once you have your statements than its just a matter of executing them against the database.
    hope this helps.

  • Help! Need to generate SQL script file in every build of every changes in database project on TFS

    Hi everyone,
                I want to accomplish a task in TFS that I need to auto generate the database changes as SQL script file in drop folder for every build.
    For ex.: If I add a table in a database and then check in the changes, I need to get that create table script in the drop folder as .sql file extension
    I want to automate the build too for every check in. Help me out and guide me a step by step procedure because since I am new to TFS build in visual studio.
    Thanks

    Check out SSDT:
    https://msdn.microsoft.com/en-us/data/tools.aspx
    It can generate a DACPAC which can be used to update a SQL Database through the commandline. To ensure that the .sql file executed is compatible with the target database schema it contains a compiled version of teh schema and will generate the change script
    on-the-fly.
    If you want, you call SqlPackage,exe to generate a SQL script if you want to inspect it before executing.
    https://msdn.microsoft.com/en-us/library/hh550080%28v=vs.103%29.aspx
    My blog: blog.jessehouwing.nl

  • How to execute a SQL procedure in UNIX

    How to execute a SQL procedure in UNIX

    Check this out..
    -Sri
    << a.sql >>
    create or replace procedure junk(nout out varchar2) is
            x varchar2(20);
    begin
            select 'Sam' into x
            from dual;
            nout := x;
    end;
    << Shell script >>
    sqlplus -s / << DOC
    scott/tiger
    variable x varchar2(20);
    set autoprint on
    @a.sql
    begin
    junk(:x);
    end;
    exit
    DOC
    << Execution of Shell SCript >>
    # sh b.sh
    Procedure created.
    PL/SQL procedure successfully completed.
    X
    Sam

  • How to run the SQL Script in SQL Prompt?

    Hi ExpertGroup,
    I have written one SQL Script name called "MySQLSCript.SQL". I want to know how to run the SQL Script in SQL Prompt?.
    Generally, I run SQL Script in PL/SQL Developer tool. But In this case, some SET command is not working/supporting in PL/SQL Developer Tool.
    Let me know, How to Run in SQl Prompt.
    Thanks & Regards,
    Senthil K Kumar.

    This is my SQL Script....
    SET COLSEP '|'
    SET LINESIZE 32767
    SET PAGESIZE 50000
    /* SET LINESIZE 3000
    SET PAGESIZE 50000
    SET DEFINE OFF */
    SET ECHO OFF
    SET FEEDBACK OFF
    --SET HEADING OFF
    SET TRIMSPOOL ON
    SET NEWPAGE NONE
    SET UNDERLINE OFF
    SPOOL &&EnterPath;
    SELECT * FROM &&TableName;
    SPOOL OFF
    SET FEEDBACK ON
    --SET DEFINE ON
    PROMPT Done.
    I am able to run this script in SQL Prompt....
    Its executing fine...
    But, If I am executing again it maynot asking for new set of data....
    alternativily its taking old values only.....
    how can i exeute with new set of data in the sql prompt.....

  • Calling a sql script file from a function.

    Hi,
    I need to call a sql script file from a user defined function. Currently i am trying to do this in Oracle SQL Developer. i tried calling with
    @ {filename}, EXECUTE IMMEDIATE etc, but nothing worked. I get the Compiler error.
    Basically my need is to call catldap.sql file so that DBMS_LDAP package gets loaded and then I can call the API functions from this.
    Please let me know if this is possible doing in a PL/SQL function.
    thanks,
    Naresh

    user784520 wrote:
    I need to call a sql script file from a user defined function. Not possible.. and it seems that you do not fully understand the client-server within the Oracle context.
    All SQL and PL/SQL are parsed and executed by an Oracle server process. The SQL and PL/SQL engines each expects a single command block at a time. Neither of these can accept a series of separate commands as a single call and then execute each in turn. The SQL engine expects a single SQL statement at a time. The PL engine expects a single PL/SQL anonymous block at a time.
    This server process also cannot break into the local file system to access script files. Nor can it hack across the network to access script files on the client.
    In order for the server process to access local files, a directory object needs to be created and the current Oracle schema needs read and/or write access on that directory object. As sound security principles apply.
    There's no PL/SQL command to execute a script. You must not mistake SQL*Plus commands (this client has a very limited vocabulary) with PL/SQL commands. SQL*Plus executes its own commands.. and send SQL and PL/SQL commands (a statement block a time) to the Oracle server process to be serviced and executed.
    It is also a very bad idea to execute external script contents from inside an Oracle server process - as that script resides externally and thus outside Oracle's security mechanisms. This means that is is pretty easy for someone to access that script, compromise it, and then have you inject and execute the contents of that script into the database.
    It is not sound security.
    Last issue - it is even worse to have application PL/SQL code dynamically creating (or trying to create) portions of the Oracle data dictionary and PL/SQL call interface.
    The database needs to be installed correctly - and this includes loading and executing the required rdbms/admin scripts during database installation. It does not make sense at all for application code to try and execute such scripts. It raises numerous issues, including having to allow that application code full and unrestricted SYS access to the database instance. A very serious security violation.
    I do not agree at all with the approach you want to use.

  • Running sql script files to re create database

    We have having around 10 sql script file that has sql statments inside it (example insert .... delete...update.... etc).Right now what we do is that in jdbc we open each script file, and read each line ,and then make jdbc call run jdbc for each sql statement inside the file.
    Wondering if there is a better way to do this.
    Right now the challenges are
    1)The process goes wrong if there is an extra semi colon ...or extra space after a statments...etc...Basically I find this way of creating data odd...
    2)it is slow because of the network traffic between application server and database server for every sql statements that gets executed.The solution for this issue is to do a batch update....But still I dont like this solution.
    Can someone give me any better idea.
    I am thinking to have all this sql script moved to a store procedure (rather than inside the sql script file) .JDBC then can pick this store procedure sql file ,and create this store procedure via jdbc, and then execute this store procedure.
    This will be faster because all the sql will be running in the databsase.Only one trip to database to call this store procedure.
    Is this a good idea ?
    thx
    m

    Manjit wrote:
    We have having around 10 sql script file that has sql statments inside it (example insert .... delete...update.... etc).Right now what we do is that in jdbc we open each script file, and read each line ,and then make jdbc call run jdbc for each sql statement inside the file.
    Wondering if there is a better way to do this.
    Right now the challenges are
    1)The process goes wrong if there is an extra semi colon ...or extra space after a statments...etc...Basically I find this way of creating data odd...
    2)it is slow because of the network traffic between application server and database server for every sql statements that gets executed.The solution for this issue is to do a batch update....But still I dont like this solution.
    Can someone give me any better idea.
    I am thinking to have all this sql script moved to a store procedure (rather than inside the sql script file) .JDBC then can pick this store procedure sql file ,and create this store procedure via jdbc, and then execute this store procedure.
    This will be faster because all the sql will be running in the databsase.Only one trip to database to call this store procedure.
    Is this a good idea ?
    thx
    mI'm not 100% sure i follow (it's Friday and i have a mild case of ADD).
    Are you suggesting having the Java application create procedures in the database on the fly? If so i would say that's not a good idea.
    Create the stored procedures in the database, have Java call them as needed to process data.
    If you need to load copious amounts of data, look in to external tables, it's possible they could come in handy for what you are doing .... or not ... again, it's hard to say given i find your description of what's currently happening somewhat confusing.

  • How to run an Oracle Script File

    Hi,
    Please anybody tell me how to run an Oracle script file (*.sql file) from Query template.
    In SQL*Plus we run a script file as @Script_file_name.sql
    how do we do it in Query Template.

    Dave,
    Please only post your question in one thread at a time....
    [SAP xMII synchronus commincation|SAP xMII synchronus commincation]
    Sam

  • How to execute an SQL query present in a string inside an ABAP program?

    hello,
    How to execute an SQL query present in a string inside an ABAP program

    Raut,
    You can execute Native SQl statements.
    Ex: To use a Native SQL statement, you must precede it with the EXEC SQL statement, and follow it with the ENDEXEC statement as follows:
    EXEC SQL [PERFORMING <form>].
      <Native SQL statement>
    ENDEXEC.
    There is no period after Native SQL statements. Furthermore, using inverted commas (") or an asterisk (*) at the beginning of a line in a native SQL statement does not introduce a comment as it would in normal ABAP syntax. You need to know whether table and field names are case-sensitive in your chosen database.
    In Native SQL statements, the data is transported between the database table and the ABAP program using host variables. These are declared in the ABAP program, and preceded in the Native SQL statement by a colon (:). You can use elementary structures as host variables. Exceptionally, structures in an INTO clause are treated as though all of their fields were listed individually.
    If the selection in a Native SQL SELECT statement is a table, you can pass it to ABAP line by line using the PERFORMING addition. The program calls a subroutine <form> for each line read. You can process the data further within the subroutine.
    As in Open SQL, after the ENDEXEC statement, SY-DBCNT contains the number of lines processed. In nearly all cases, SY-SUBRC contains the value 0 after the ENDEXEC statement. Cursor operations form an exception: After FETCH, SY-SUBRC is 4 if no more records could be read. This also applies when you read a result set using EXEC SQL PERFORMING.
    EXEC SQL PERFORMING loop_output.
      SELECT connid, cityfrom, cityto
      INTO   :wa
      FROM   spfli
      WHERE  carrid = :c1
    ENDEXEC.
    Pls. Mark If useful

  • How to execute this SQL Query in ABAP Program.

    Hi,
    I have a string which is the SQL Query.
    How to execute this sql Query (SQL_STR) in ABAP Program.
    Code:-
    DATA: SQL_STR type string.
    SQL_STR = 'select * from spfli.'.
    Thanks in Advance,
    Vinay

    Hi Vinay
    Here is a sample to dynamically generate a subroutine-pool having your SQL and calling it.
    REPORT dynamic_sql_example .
    DATA: BEGIN OF gt_itab OCCURS 1 ,
    line(80) TYPE c ,
    END OF gt_itab .
    DATA gt_restab TYPE .... .
    DATA gv_name(30) TYPE c .
    DATA gv_err(120) TYPE c .
    START-OF-SELECTION .
    gt_itab-line = 'REPORT generated_sql .' .
    APPEND gt_itab .
    gt_itab-line = 'FORM exec_sql CHANGING et_table . ' .
    APPEND gt_itab .
    gt_itab-line = SQL_STR .
    APPEND gt_itab .
    gt_itab-line = 'ENDFORM.' .
    APPEND gt_itab .
    GENERATE SUBROUTINE POOL gt_itab NAME gv_name MESSAGE gv_err .
    PERFORM exec_sql IN PROGRAM (gv_name) CHANGING gt_restab
    IF FOUND .
    WRITE:/ gv_err .
    LOOP AT gt_result .
    WRITE:/ .... .
    ENDLOOP .
    *--Serdar

Maybe you are looking for

  • Problem with output formatting.

    Hi all, I have an output as shown below. R1             R2                            R3                            R4           R5           R6            R7 20000001      27.02.2007     3326          180080     D4           20000001     27.02.2007 

  • How can I get Itunes7 back on my computer after a hard drive crash?

    I really don't want to be forced to go to Itunes 8. Was very satisfied with using version 7. I still hear there are many problems with version 8. I still have the CD for version 6. Would it be better, or more safe to stay with 6? But I liked the feat

  • Program to Check AppleTV Compatibility of an MP4?

    Is there a program I can use to "look" at an MP4 to determine if it will be playable on an AppleTV...If it is not, can it tell me what needs to be fixed? I have a video which hasn't been showing on my ATV, if I try to sync ITunes says it cannot be pl

  • Problem with calculation in report.

    please let me know about below code . What can be possible errors .Because I didn't get true calculations . My purpose is to get ztab-pvprs for every material. CLEAR atab . REFRESH atab .   SELECT smblnr sbudat z~matnr          zwerks zbwart z~menge

  • SQL Command problem in Application Express 3.2.0.00.27

    To Oracle Application Express Development Team, Yesterday I installed Oracle Application Express 3.2.0.00.27. While doing my r&d, I came across one problem in SQL Command. For example I wanted to run sql "select * from tab" When I checked "Autocommit