[英]Change SQL Server stored procedure in C#
I want to add a new column in an existing stored procedure using C# and save it back to the SQL Server. 我想使用C#在现有存储过程中添加一个新列,并将其保存回SQL Server。
eg I have this SP: 我有这个SP:
ALTER PROCEDURE [dbo].[usp_SP1]
AS
BEGIN
CREATE TABLE #tbl1(a int, b int)
SELECT
a, b
FROM #tbl1
END
Now I want to automatically add a new column eg xx type TEXT, so the output is 现在我想自动添加一个新列,例如xx类型TEXT,因此输出为
ALTER PROCEDURE [dbo].[usp_SP1]
AS BEGIN
CREATE TABLE #tbl1
(a int, b int, xx TEXT)
SELECT
a, b, xx
FROM #tbl1
END
Does anyone know how to do that? 有谁知道这是怎么做到的吗?
Thanks 谢谢
When you've defined your database object and a stored procedure object you can create the sp right from managed code: 定义数据库对象和存储过程对象后,可以从托管代码创建sp权限:
StoredProcedure sp = new StoredProcedure(myDB, "NameOfSproc");
sp.TextMode=False;
sp.AnsiNullsStatus=False;
sp.QuotedIdentifierStatus=false;
//add some parameters
StoredProcedureParameter p;
p = new StoredProcedureParameter(sp, "@MyID", Int);
//add the parameters to the sproc
sp.Parameters.Add(p);
sp.TextBody = "SELECT blah FROM MyTable WHERE ID=@myID";
sp.CreatE();
Hopefully, that is incomplete example code. 希望这是不完整的示例代码。 Your SP will return an empty resultset.
您的SP将返回一个空结果集。
To answer a underlying question: How do I execute a DDL statement, I suggest this answer. 回答一个基本问题:我如何执行DDL语句,我建议这个答案。
It's just like running a query, except executing a create/alter script returns no results. 它就像运行查询一样,除了执行create / alter脚本没有返回任何结果。
Note per JonH: nothing was mentioned about using command parameters or stored procedure parameters, so I didn't address either of them.
注意每个JonH:没有提到使用命令参数或存储过程参数,所以我没有解决它们中的任何一个。 This was a short-and-simple method to alter a stored procedure - that is, run an SQL script to do so - from C#.
这是一个简短的方法来改变存储过程 - 也就是说,运行一个SQL脚本来实现这一点 - 来自C#。
Your script string can be constructed using any method you choose. 您可以使用您选择的任何方法构建脚本字符串。 If you are talking about dynamically parsing a stored procedure from a database, reassembling it with altered parts, then resubmitting it, you should probably revise the way you asked your question.
如果您正在讨论从数据库动态解析存储过程,使用更改的部分重新组装它,然后重新提交它,您可能应该修改您提出问题的方式。 You would have to know the structure of your script;
您必须知道脚本的结构; there's no general way to "insert a column in unspecified places in some existing SP".
没有一般方法“在某些现有SP中的未指定位置插入列”。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.