Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Execute multiple queries in single Oracle command in C#

I am using visual studio 2013 and oracle database.I want execute multiple create table queries at once in single oraclecommand is it possible ? I am trying following but not working

OracleCommand cmd = new OracleCommand();
cmd.Connection = con;
cmd.CommandText = "create table test(name varchar2(50) not null)"+"create table test2(name varchar2(50) not null)"; 
//+ "create table test3(name varchar2(50) not null)"+"create table test3(name varchar2(50) not null)";
cmd.CommandType = CommandType.Text;
cmd.ExecuteNonQuery();

Got error at cmd.ExecuteNonQuery();

like image 567
Hanni Avatar asked Aug 10 '15 10:08

Hanni


People also ask

How do I run multiple SQL queries in Oracle?

In SqlDeveloper preferences: Tools > Preferences > Database > Worksheet check the option for New Worksheet to use unshared connction . This will allow you to execute multiple queries at the same time, each in each tab.

Can two statements run in one SQL script?

You can just run multiple SQL statements one after the other in a stored procedure.


1 Answers

In order to execute more than one command put them in begin ... end; block. And for DDL statements (like create table) run them with execute immediate. This code worked for me:

OracleConnection con = new OracleConnection(connectionString);
con.Open();

OracleCommand cmd = new OracleCommand();
cmd.Connection = con;
cmd.CommandText =
    "begin " +
    "  execute immediate 'create table test1(name varchar2(50) not null)';" +
    "  execute immediate 'create table test2(name varchar2(50) not null)';" +
    "end;";
cmd.CommandType = CommandType.Text;
cmd.ExecuteNonQuery();
con.Close();

More info: Executing SQL Scripts with Oracle.ODP

like image 59
Ponder Stibbons Avatar answered Sep 22 '22 10:09

Ponder Stibbons