I'm working on some code that creates procedures with C#. When I try to run my code:
StringBuilder sbSP1 = new StringBuilder();
sbSP1.AppendLine("CREATE PROCEDURE " + ProcN + "DELETE @id int=0 AS BEGIN DELETE FROM " + tname + " WHERE " + PK + " = @id END");
SqlConnection connection = new SqlConnection(connectionString);
using (SqlCommand cmd = new SqlCommand(sbSP1.ToString(), connection))
{
connection.Open();
cmd.CommandType = CommandType.Text;
cmd.ExecuteNonQuery();
connection.Close();
}
This part doesn't work. It throws an exception:
System.Data.SqlClient.SqlException: 'Incorrect syntax near '='.'
But when I try to run this part:
StringBuilder sbSP3 = new StringBuilder();
sbSP3.AppendLine("CREATE PROCEDURE " + ProcN + "GET AS BEGIN SET NOCOUNT ON; SELECT " + columns + " from " + tname + " END");
SqlConnection connection = new SqlConnection(connectionString);
using (SqlCommand cmd = new SqlCommand(sbSP3.ToString(), connection))
{
connection.Open();
cmd.CommandType = CommandType.Text;
cmd.ExecuteNonQuery();
connection.Close();
}
it runs correctly.
Where is my mistake in the first snippet of code?
sbSP1.ToString()?CREATE PROCEDURE @ProcName AS ..., you'll just get a syntax error.sbSP1.ToString()at the time you assign it to theSqlCommand, but my initial hunch was thatProcNorPKcontained a space, or some invalid character.