I am trying to create a stored procedure in SQL server from a C# winforms application. This is the function I have so far.
public void CreateStoredProcedure(string SPname)
{
try
{
string query = "CREATE PROCEDURE " + SPname + " AS SELECT * FROM People WHERE Address='Mumbai'";
connection.Open();
var command = new SqlCommand();
command.CommandType = CommandType.Text;
command.CommandText = "EXEC " + query;
command.ExecuteNonQuery();
}
finally
{
connection.Close();
}
}
Am I doing this right? I get an error message every time I try to achieve this.
Hey thanks a lot guys!! Its working now.. This is the code that finally did it..
public void CreateStoredProcedure(string SPname)
{
try
{
string query = "CREATE PROCEDURE " + SPname + " AS SELECT * FROM People WHERE Address='Mumbai'";
connection.Open();
var command = new SqlCommand();
command.Connection = connection;
command.CommandText = query;
command.ExecuteNonQuery();
var adapter = new SqlDataAdapter(command);
adapter.Fill(dt);
dgv.DataSource = dt;
}
finally
{
connection.Close();
}
}
much appreciated! :)
CommandType.Textis by default.command.Connection = connection;. You didn't connect yourSqlCommandwith yourSqlConnection.