Programmatically retrieve SQL Server stored procedure source that is identical to the source returned by the SQL Server Management Studio gui?

后端 未结 9 2029
孤独总比滥情好
孤独总比滥情好 2020-11-30 20:38

Any pointers on how I can programmatically get exactly the identical stored procedure source from SQL Server 2005, as when I right-click on that stored procedure in SQL Serv

9条回答
  •  栀梦
    栀梦 (楼主)
    2020-11-30 21:19

    You said programmatically, right? I hope C# is ok. I know you said that you tried SMO and it didn't quite do what you wanted, so this probably won't be perfect for your request, but it will programmatically read out legit SQL statements that you could run to recreate the stored procedure. If it doesn't have the GO statements that you want, you can probably assume that each of the strings in the StringCollection could have a GO after it. You may not get that comment with the date and time in it, but in my similar sounding project (big-ass deployment tool that has to back up everything individually), this has done rather nicely. If you have a prior base that you wanted to work from, and you still have the original database to run this on, I'd consider tossing the initial effort and restandardizing on this output.

    using System.Data.SqlClient;
    using Microsoft.SqlServer.Management.Common;
    using Microsoft.SqlServer.Management.Smo;
    …
    string connectionString = … /* some connection string */;
    ServerConnection sc = new ServerConnection(connectionString);
    Server s = new Server(connection);
    Database db = new Database(s, … /* database name */);
    StoredProcedure sp = new StoredProcedure(db, … /* stored procedure name */);
    StringCollection statements = sp.Script;
    

提交回复
热议问题