views:

383

answers:

5

Is there a way to determine programmatically if a SQL Server stored procedure parameter has a default? (Bonus points if you can determine what the default is.) SqlCommandBuilder.DeriveParameters() doesn't even try.

Thanks in advance for your help!

EDIT: I honestly don't care if it's a SQL Query, an SMO object, etc.

+1  A: 

Run the builtin sp_help stored procedure?

Bernard Vander Beken
Where in the resultset for sp_help does it indicate whether a parameter has a default?
GuyBehindtheGuy
does list the parameter - but not whether or not they have a default value, and what it would be :-(
marc_s
+5  A: 
marc_s
Hmm...have you actually run this? On SQL 2008 with db compatability set to "100", `has_default_value` is 0 for every row, even though the parameter definitely has a default!
GuyBehindtheGuy
Yes I ran it - unfortunately, all my sprocs never have default values, so I couldn't really verify - let me check...
marc_s
Wow. The recommended way to do it is to _parse the body of the stored procedure_?! That sucks.
GuyBehindtheGuy
+6  A: 

I found a way using SMO:

Server srv; 
srv = new Server("ServerName"); 

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

var Params = db.StoredProcedures["MyStoredProc"].Parameters;

foreach(StoredProcedureParameter param in Params) {
    Console.WriteLine(param.Name + "-" + param.DefaultValue);
}
GuyBehindtheGuy
+1 excellent ! Good to know
marc_s
+1  A: 

For stored procedures, I believe you would have to write something that parses T-SQL, or use the T-SQL parser that Microsoft provides.

The parser and script generator live in two assemblies. The Microsoft.Data.Schema.ScriptDom contains provider agnostic classes and the Microsoft.Data.Schema.ScriptDom.Sql assembly contain classes for the parser and script generator that are SQL Server specific.

How to specifically use this to identify the parameters and whether they're defaulted isn't covered and would be something you'd have to work on (probably with a deal of effort) using the sample code.

dlamblin
Interesting idea. I'd need a license to VSTS Database Edition, though. :-)
GuyBehindtheGuy
+1  A: 

This is kind of a hack, but you could always just give optional parameters a special name like:

@AgeOptional = 15

...then write a simple method that checks a parameter to see if it's optional. Not ideal, but given the situation, it might actually be a decent solution.

birdus