I'm trying to develop a little app that will run a CREATE PROCEDURE script. A simple example:
IF EXISTS (SELECT * FROM sysobjects WHERE type = 'P' AND name = 'ap_get_roles_in_system')
BEGIN
DROP Procedure [dbo].[ap_get_roles_in_system]
END
GO
CREATE PROCEDURE [dbo].[ap_get_roles_in_system]
(
@system_id int
)
AS
SELECT * FROM roles
GO
GRANT EXEC ON [dbo].[ap_get_roles_in_system] TO PUBLIC
GO
If I load this text up in a string, and run it by way of ExecuteNonQuery(), the first item, which drops the stored procedure, works fine, but instead of running the Create it finds a syntax error with the parameter of the stored procedure, namely: it hasn't been declared.
In short, instead of trying to run the CREATE, it is somehow trying to run the script as a script, not a CREATE. Not sure what the correct wording would be.
The script above works great if pasted into Sql Management Studio.
Here's the code I am executing:
public string RunSql(string Sql)
{
string result = string.Empty;
_conn.Open();
SqlCommand cmd = new SqlCommand(Sql, _conn);
cmd.CommandType = CommandType.Text;
try
{
cmd.ExecuteNonQuery();
result = "Succeeded";
}
catch (SqlException ex)
{
result = ex.Message;
}
return result;
}
GO. You might also find its support for scripting variables useful for running scripts with multiple servers or databases.