Get stored procedure parameters by either C# or SQL?

前端 未结 4 985
你的背包
你的背包 2020-12-08 18:25

I was hoping to find an easy way to get a parameter list of a stored procedures parameters. If the procedure has 3 paramaters, I want a list like this:

param

4条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-08 18:59

    You can do this without ever touching SqlConnection, which I find is a bonus.

    This uses the SqlServer.Management.Smo namespace, so you need a reference to Microsoft.SqlServer.ConnectionInfo, Microsoft.SqlServer.Management.Sdk, and Microsoft.SqlServer.Smo in your project.

    Then use the following code:

    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;
        }
    }
    

提交回复
热议问题