通过C#或SQL获取存储过程参数?

问题描述:

我希望能找到一个简单的方法来获取存储过程参数的参数列表。如果程序有3个PARAMATERS,我希望像这样的列表:通过C#或SQL获取存储过程参数?

参数1
参数2
参数3

这将是最好能够做到这在C#代码,但SQL足以作为好。想法?

select * from information_schema.parameters 
where specific_name='your_procedure_name' 
+0

有许多方法在sql中做到这一点。请参阅此帖以了解更多方法https://madhivanan.wordpress.com/2016/10/14/different-methods-to-get-parameter-list-of-a-stored-procedure/ – Madhivanan 2016-10-14 06:56:00

如果您熟悉企业图书馆,有一个很好的方法,它允许使用Data Access Application BlockDiscoverParameters()

DbCommand command = new DbCommand(); 
command.CommandText = @"myStoredProc"; 
command.CommandType = CommandType.StoredProcedure; 

Database database = new SqlDatabase(myConnectionString); 
database.DiscoverParameters(command); 
// ... 

有些链接可能会有所帮助:

  1. DiscoverParameters Method;
  2. Microsoft.Practices.EnterpriseLibrary.Data Namespace

上述链接指的是EntLib 3.1。根据您使用的.NET Framework版本,您也可以考虑按照this link下载正确的EntLib版本。

对于SQL Server,这应该可以工作。

private void ListParms() 
{ 
    SqlConnection conn = new SqlConnection("my sql connection string"); 
    SqlCommand cmd = new SqlCommand("proc name", conn); 
    cmd.CommandType = CommandType.StoredProcedure; 
    conn.Open(); 
    SqlCommandBuilder.DeriveParameters(cmd); 
    foreach (SqlParameter p in cmd.Parameters) 
    { 
     Console.WriteLine(p.ParameterName); 
    } 
} 
+0

在我的情况下,我添加了这个在我的foreach中:if(p.ParameterName ==“@RETURN_VALUE”)continue; – 2016-05-27 17:42:46

你可以做到这一点,而无需触摸SqlConnection,我发现这是一个奖金。

这使用SqlServer.Management.Smo命名空间,因此您需要在项目中引用Microsoft.SqlServer.ConnectionInfo,Microsoft.SqlServer.Management.SdkMicrosoft.SqlServer.Smo

然后使用下面的代码:

Server srv = new Server("serverNameHere"); 
srv.ConnectionContext.AutoDisconnectMode = AutoDisconnectMode.NoAutoDisconnect; 
srv.ConnectionContext.LoginSecure = false; //if using username/password 
srv.ConnectionContext.Login = "username"; 
srv.ConnectionContext.Password = "password"; 
srv.ConnectionContext.Connect(); 

Database db = srv.Databases["databaseNameHere"]; 

foreach(StoredProcedure sp in db.StoredProcedures) 
{ 
    foreach(var param in sp.Parameters) 
    { 
     string paramName = param.Name; 
     var dataType = param.DataType; 
     object defaultValue = param.DefaultValue; 
    } 
} 
+0

我在这里找到了这些程序集:C:\ Program Files \ Microsoft SQL Server \ 100 \ SDK \ Assemblies – Moondustt 2013-12-06 13:05:48