C#以编程方式更改存储过程

时间:2018-06-06 14:38:57

标签: c# sql sql-server stored-procedures sql-server-2014

我有以下C#代码应该允许我修改(更改)我的存储过程:

SqlConnection sqlCon = new SqlConnection(ConfigurationManager.ConnectionStrings["sqlConnection"].ConnectionString);
ServerConnection srvCon = new ServerConnection(sqlCon);

sqlCon.Open();

Server srv = new Server(srvCon);
Database db = srv.Databases[sqlCon.Database];
StoredProcedure sp = new StoredProcedure(db, "spRDLDataFetcher");

sp.TextMode = false;
sp.AnsiNullsStatus = false;
sp.QuotedIdentifierStatus = false;
sp.TextBody = "SELECT blah FROM MyTable WHERE ID=1";
sp.Alter();

但是,sp.Alter()调用会抛出此错误:

  

Microsoft.SqlServer.Management.Smo.FailedOperationException:'更改了StoredProcedure' dbo.spRDLDataFetcher'。 '

     

内部异常:InvalidSmoOperationException:您无法对状态为“创建”中的对象执行操作Alter。

为了让它改变(更新)该存储过程我缺少什么?

1 个答案:

答案 0 :(得分:1)

好吧所以我发现了为什么它没有更新它。看来,无论出于何种原因,在我覆盖textBody之前,它需要 sp.Refresh(); First

SqlConnection sqlCon = new SqlConnection(ConfigurationManager.ConnectionStrings["sqlConnection"].ConnectionString);
ServerConnection srvCon = new ServerConnection(sqlCon);

sqlCon.Open();

Server srv = new Server(srvCon);
Database db = srv.Databases[sqlCon.Database];
StoredProcedure sp = new StoredProcedure(db, "spRDLDataFetcher");

sp.TextMode = false;
sp.AnsiNullsStatus = false;
sp.QuotedIdentifierStatus = true;
sp.ImplementationType = ImplementationType.TransactSql;
sp.Schema = "dbo";

sp.Refresh(); //What was needed to make work
string orgSPText = sp.TextBody;

sp.TextBody = "SELECT blah FROM MyTable WHERE ID=1";
sp.Recompile = true;
sp.Alter();

sp.Recompile = true; 确实不需要。它会在没有它的情况下工作,但我喜欢把它留在那里,只是为了踢和咯咯笑。