Parse sql parameters from commandtext

这一生的挚爱 提交于 2020-01-15 03:08:28

问题


Is it possible to parse sql parameters from plain commandtext?

e.g.

//cmdtext = SELECT * FROM AdWorks.Countries WHERE id = @id
SqlCommand sqlc = new SqlCommand(cmdtext);
SqlParameterCollection parCol = sqlc.Parameters //should contain now 1 paramter called '@id'

回答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.




回答2:


I ended up with this extention method (since I don't think there's a built in function):

public static class SqlParExtension
{
    public static void ParseParameters(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;



回答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 = { new SqlParameter("@id", qid), 
new SqlParameter("@otherValue", value) };

// Add teh parameters to the command.
sqlc.Parameters.AddRange(parameters)



回答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 :-).



来源:https://stackoverflow.com/questions/22088320/parse-sql-parameters-from-commandtext

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!