Is there a way to get stored procedures from a SQL Server 2005 Express database using C#? I would like to export all of this data in the same manner that you can script it o
You can use:
DataTable dtProcs = sqlConn.GetSchema("Procedures", new string[] { databaseName });
DataTable dtProcParams = sqlConn.GetSchema("ProcedureParameters", new string[] { databaseName });
You can also get all sorts of other schema info like tables, indexes etc. if you need them.
You can get info on GetSchema() here and info on the SQL Server Schema Collections here
Edit: Sorry, this doesn't help with actually scripting the info, but I guess it's useful info to have.
You can use SMO for that. First of all, add references to these assemblies to your project:
They are located in the GAC (browse to C:\WINDOWS\assembly folder).
Use the following code as an example of scripting stored procedures:
using System;
using System.Collections.Generic;
using System.Data;
using Microsoft.SqlServer.Management.Smo;
class Program
{
static void Main(string[] args)
{
Server server = new Server(@".\SQLEXPRESS");
Database db = server.Databases["Northwind"];
List<SqlSmoObject> list = new List<SqlSmoObject>();
DataTable dataTable = db.EnumObjects(DatabaseObjectTypes.StoredProcedure);
foreach (DataRow row in dataTable.Rows)
{
string sSchema = (string)row["Schema"];
if (sSchema == "sys" || sSchema == "INFORMATION_SCHEMA")
continue;
StoredProcedure sp = (StoredProcedure)server.GetSmoObject(
new Urn((string)row["Urn"]));
if (!sp.IsSystemObject)
list.Add(sp);
}
Scripter scripter = new Scripter();
scripter.Server = server;
scripter.Options.IncludeHeaders = true;
scripter.Options.SchemaQualify = true;
scripter.Options.ToFileOnly = true;
scripter.Options.FileName = @"C:\StoredProcedures.sql";
scripter.Script(list.ToArray());
}
}
See also: SQL Server: SMO Scripting Basics.
I think this is what you're really looking for:
select SPECIFIC_NAME,ROUTINE_DEFINITION from information_schema.routines
There are a ton of other useful columns in there too...
Assuming you have SqlConnection
object called sqlCon, simplest way is to call sqlCon.GetSchema("Procedures")
This blog post suggests running this against your database:
select * from sys.procedures
Just read the output of SELECT NAME from SYS.PROCEDURES , then call EXEC sp_HelpText SPNAME for each stored procedure, you'll get a record set with one line of text per row.