Click here to Skip to main content
15,888,263 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
C#
When i execute the code its giving runtime error.

But when i execute same commands which i took commands from debugging mode and paste in SQL server. It is executing fine without errors.

Please give me the solution.

string s = "create database dbTest  \r\n GO \r\n Use dbTest \r\n GO";
        SqlCommand cmd = new SqlCommand(s, con);
        cmd.CommandType = CommandType.Text;
        con.Open();
        cmd.ExecuteNonQuery();
        con.Close();`


What I have tried:

string s = "create database dbTest \r\n GO \r\n Use dbTest \r\n GO";
SqlCommand cmd = new SqlCommand(s, con);
cmd.CommandType = CommandType.Text;
con.Open();
cmd.ExecuteNonQuery();
con.Close();`
Posted
Updated 27-Apr-16 9:03am

1 solution

"GO" is a SQL-Server-Management-Studio specific command and not part of T-SQL.

If you would want to use SQL-scripts with "GO"-commands please refer to this:
c# - Execute a large SQL script (with GO commands) - Stack Overflow[^]

Otherwise you would have to execute these statements separately (and I suggest using using-statements for Sql****-objects):

C#
using (var connection = new SqlConnection("your connection string here"))
{
    connection.Open();

    using (var command = connection.CreateCommand())
    {
        command.CommandText = "CREATE DATABASE dbTest;";
        command.ExecuteNonQuery();

        command.CommandText = "USE dbTest;";
        command.ExecuteNonQuery();
    }
}

The connection string should best not be hardcoded at the indicated position but be read from a configuration file.

Note that the "USE"-command will affect only the following commands on the same connection, so in this example it's pretty useless.
 
Share this answer
 
v4
Comments
Member 9409254 27-Apr-16 15:06pm    
Hi friend, thanks for quick responce.

I have tried that but its giving error.
Database 'dbTest' does not exist. Make sure that the name is entered correctly.
Please take a look into VIsual Studio.
Sascha Lefèvre 27-Apr-16 15:09pm    
After I wrote the answer I became unsure myself and was just about to test it - I assume that the two statements can't be "batched" - so you would have to execute them separately. I'll update the answer after I tested it.
Member 9409254 27-Apr-16 15:16pm    
Thanks Friend
Sascha Lefèvre 27-Apr-16 15:22pm    
Answer updated, please take a look.
Member 9409254 27-Apr-16 15:27pm    
Can't i execute at a time?
My requirement : execute both at once not seperately.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900