简体   繁体   中英

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.

eg I have this 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

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:

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.

To answer a underlying question: How do I execute a DDL statement, I suggest this answer.

  • Create your SQL script as a String.
  • Create a SqlConnection to your database and open it.
  • Create an SqlCommand object. Set its Text property to your script string. Set its Connection property to your SqlConnection object.
  • Call the ExecuteNonQuery() method on your SqlCommand object.

It's just like running a query, except executing a create/alter script returns no results.

Note per JonH: nothing was mentioned about using command parameters or stored procedure parameters, so I didn't address either of them. This was a short-and-simple method to alter a stored procedure - that is, run an SQL script to do so - from 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".

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM