I'm attempting to retrieve the DefaultValue of all the parameters in a StoredProcedure. My application is build in C# .NET accessing a Microsoft SQL 2008 Database.
I use the SqlCommandBuilder.DeriveParameters to get most of the parameter information rather efficiently however it does not return the "DefaultValue" of a parameter so I've resorted to SMO to get that particular property.
Here's my current code :
Server svr = new Server(new ServerConnection(new SqlConnection(ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString)));
StoredProcedure sp = svr.Databases["MyDatabase"].StoredProcedures["mySproc", "myScheme"];
svr.SetDefaultInitFields(typeof(StoredProcedureParameter), "Name");
svr.SetDefaultInitFields(typeof(StoredProcedureParameter), "DefaultValue");
Dictionary<string, string> defaultValueLookup = new Dictionary<string, string>();
foreach (StoredProcedureParameter parameter in sp.Parameters)
{
string defaultValue = parameter.DefaultValue;
string parameterName = parameter.Name;
defaultValueLookup.Add(parameterName, defaultValue);
}
However, this is very slow even after I added the svr.SetDefaultInitFields optimization (which did make a significant improvement ~10x improvement).
Anybody got further optimization ideas?
I had a smiliar problem and found that if you use...
svr.SetDefaultInitFields(typeof(StoredProcedure), false)
It's way faster. I'm asuming that with any other options it actually fetches everything but if you switch it off then just get your params the speed increase is huge. Mine when from 5-6 secs to 0.5 secs for a 10 param sp. Still not quite perfect but livable with.
EDIT
Since playing with this a little more I found that the typeof(StoredProcedure)
level appraoch works the best. In my tests using the typeof(StoreedProcedureParameter)
option was consistently 1.5 secs or so compared to the 0.5 secs or so with the typeof(StoredProcedure)
version.
I'd be interested if anyone could tell me why?
You could use a parser to retrieve the default values from the stored procedure, e.g. Microsoft.Data.Schema.ScriptDom
.
来源:https://stackoverflow.com/questions/8528472/how-can-i-retrieve-sql-stored-procedure-parameters-with-smo-more-efficently