Question

I'm developing a website that I do not have remote access to its SQL Server. When I try to create a new procedure in my own database I got stuck this error:

CREATE/ALTER PROCEDURE must be the first statement in a query batch.

That's because of T-SQL scripts containing "GO" statement....

Using the Server Management Objects (SMO), the problem still exists for me. How can I create a stored procedure in my database without using Go statement and without using SMO?

This is my code:

    SqlConnection Con = new SqlConnection(ConnectionString);
    Con.Open();
    SqlCommand cmd;
    string sql = "CREATE Procedure [dbo]......";
    cmd = new SqlCommand(sql, Con);
    cmd.ExecuteNonQuery();
    Con.Close();

Thanks.

Was it helpful?

Solution

After much searching I finally found the answer. You can change the current database for an open SqlConnection very easily:

connection.ChangeDatabase("YourDB");

An example:

private static void ConctDatabase(string connectionString)
{
    using (SqlConnection conn = new SqlConnection(connectionString))
    {
        conn.Open();
        MessageBox.Show("Database: {0}", conn.Database);
        conn.ChangeDatabase("Northwind");
        MessageBox.Show("Database: {0}", conn.Database);
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top