从commandtext解析sql参数

时间:2014-02-28 06:55:59

标签: c# sql sql-server parameters sqlcommand

是否可以从plain commandtext解析sql参数?

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'

4 个答案:

答案 0 :(得分:4)

如果SQL Server可用,最好的选择可能是询问服务器它的想法;服务器具有内置的解析和元数据功能,例如sp_describe_undeclared_parameters

答案 1 :(得分:1)

我最终得到了这种扩展方法(因为我认为没有内置函数):

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

用法:

//cmdtext = SELECT * FROM AdWorks.Countries WHERE id = @id
SqlCommand sqlc = new SqlCommand(cmdtext);
sqlc.ParseParameters();

sqlc.Parameters["@id"].Value = value;

答案 2 :(得分:0)

我必须确保这一点,但我确定你必须在命令中添加参数范围。就像我说我将不得不回来,但你可以尝试做类似的事情:

// 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)

答案 3 :(得分:0)

非常欢迎您查看我的 VS2015 extension, QueryFirst ,它会从.sql文件生成包装类,直接从您的sql获取参数声明 。您需要在请求的--designTime部分声明参数,然后再次直接将它们作为输入发现到Execute(),GetOne()或ExecuteScalar()方法。这些方法返回带有含义属性名称的POCO。在任何地方都有智能感知,你不必在其他很多优点中键入一行参数代码,连接代码,命令代码或读者代码 :()