Ili*_*nin 0 c# asp.net stored-procedures
我正在编写一个通用函数,用于将查询字符串直接输入到sproc中.该算法相当基本 - 循环查询键,将它们用作参数名称,而值用作参数值.所以它看起来像这样:
ArrayList pars = new ArrayList();
SqlParameter p;
int tryInt;
for (int i = 0; i < req.QueryString.Count; i++)
{
key = req.QueryString.AllKeys[i];
if (int.TryParse(req[key], out tryInt))
{
p = new SqlParameter("@" + key, SqlDbType.Int);
p.Value = tryInt;
pars.Add(p);
}
}
Run Code Online (Sandbox Code Playgroud)
到目前为止,这工作正常,除了当然所有查询键必须匹配sproc的参数,如果他们不这样做我得到一个SQL异常说类似的东西
@someParameter is not a parameter for procedure some_sproc
Run Code Online (Sandbox Code Playgroud)
但是我需要能够在查询字符串中传入不会传递给sproc的变量,所以我需要一种方法来"忽略"它们.
有没有办法测试给定的存储过程是否需要某个参数?这样我就能沿着这些方向做点什么
if (paramExists("@" + key, "some_sproc") && int.TryParse(req[key], out tryInt))
{
p = new SqlParameter("@" + key, SqlDbType.Int);
p.Value = tryInt;
pars.Add(p);
}
Run Code Online (Sandbox Code Playgroud)
您可以使用SqlCommandBuilder来获取SP参数:
using (SqlConnection sqlConn = new SqlConnection(yourConnStr))
using (SqlCommand sqlCmd = new SqlCommand(yourProcedureName, sqlConn))
{
sqlConn.Open();
sqlCmd.CommandType = CommandType.StoredProcedure;
SqlCommandBuilder.DeriveParameters(sqlCmd);
// now you can check parameters in sqlCmd.Parameters
}
Run Code Online (Sandbox Code Playgroud)
更多细节在这里