Parse Sql Parameters From Commandtext
Solution 1:
If a SQL Server is available, the best option may be to simply ask the server what it thinks; the server has parsing and metadata functions built in, for example sp_describe_undeclared_parameters.
Solution 2:
I ended up with this extention method (since I don't think there's a built in function):
publicstaticclassSqlParExtension
{
publicstaticvoidParseParameters(this SqlCommand cmd)
{
var rxPattern = @"(?<=\= |\=)@\w*";
foreach (System.Text.RegularExpressions.Match item in System.Text.RegularExpressions.Regex.Matches(cmd.CommandText, rxPattern))
{
var sqlp = new SqlParameter(item.Value, null);
cmd.Parameters.Add(sqlp);
}
}
}
usage:
//cmdtext =SELECT*FROM AdWorks.Countries WHERE id =@id
SqlCommand sqlc =new SqlCommand(cmdtext);
sqlc.ParseParameters();
sqlc.Parameters["@id"].Value=value;
Solution 3:
I will have to make sure about this but I'm sure you must add the range of parameters to the command. Like I say I will have to come back with this but you can try doing something like:
// Create a collection of parameters with the values that the procedure is expecting in your SQL client.
SqlParameter[] parameters = { newSqlParameter("@id", qid),
newSqlParameter("@otherValue", value) };
// Add teh parameters to the command.
sqlc.Parameters.AddRange(parameters)
Solution 4:
You would be very welcome to have a look at my VS2015 extension, QueryFirst, that generates wrapper classes from .sql files, harvesting parameter declarations directly from your sql. You need to declare your parameters in the --designTime section of your request, but then you find them again directly as inputs to the Execute(), GetOne() or ExecuteScalar() methods. These methods return POCOs with meaningul property names. There's intellisense everywhere, and you don't have to type a line of parameter code, or connection code, or command code, or reader code, among NUMEROUS OTHER ADVANTAGES :-).
Post a Comment for "Parse Sql Parameters From Commandtext"