gra*_*ady 50 c# sql parameters stored-procedures sql-server-2008
我希望找到一种简单的方法来获取存储过程参数的参数列表.如果程序有3个参数,我想要一个这样的列表:
param1
param2
param3
最好能够在C#代码中执行此操作,但SQL也足够了.想法?
Mad*_*nan 74
select * from information_schema.parameters
where specific_name='your_procedure_name'
Run Code Online (Sandbox Code Playgroud)
另请参阅此帖子以了解更多方法 https://exploresql.com/2016/10/14/different-methods-to-get-parameter-list-of-a-stored-procedure/
Rob*_*cus 57
对于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);
}
}
Run Code Online (Sandbox Code Playgroud)
gun*_*171 10
您可以在不触及SqlConnection的情况下执行此操作,我发现这是一个奖励.
这里使用了SqlServer.Management.Smo命名空间,所以你需要一个参照Microsoft.SqlServer.ConnectionInfo,Microsoft.SqlServer.Management.Sdk以及Microsoft.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;
}
}
Run Code Online (Sandbox Code Playgroud)
如果您熟悉Enterprise Library,那么可以使用数据访问应用程序块来使用DiscoverParameters().
DbCommand command = new DbCommand();
command.CommandText = @"myStoredProc";
command.CommandType = CommandType.StoredProcedure;
Database database = new SqlDatabase(myConnectionString);
database.DiscoverParameters(command);
// ...
Run Code Online (Sandbox Code Playgroud)
一些可能有用的链接:
以上链接指的是EntLib 3.1.根据您正在使用的.NET Framework版本,您可能还会考虑在此链接下为您下载正确的EntLib版本.