将存储过程作为字符串传递

时间:2013-03-13 19:52:06

标签: c# sql-server-2005

如何将存储过程与作为字符串的参数一起传递给函数?

我试过这段代码,但没有运气..

这是业务访问层代码

 try
 {
     string Query_string = "SP_InsertOffer_Tab @offer_name ='" + this.offer_name +"',  @offer_price = " + this.offer_price + ",@start_date = '" + this.start_date + 
 "',@end_date = '" + this.end_date + "'";

     int result = DbAcess.Insert_Query(Query_string);
     return result;
 }
 catch (Exception ex)
 {
    throw ex;
 }
 finally
 {
    DbAcess = null;
 }

数据库层代码如下

public int Insert_Query(string strSQL)
{
    SqlConnection con = new SqlConnection();
    con = OpenConnection();

    try
    {
        sqlcmd = new SqlCommand();
        sqlcmd.Connection = con;
        sqlcmd.CommandType = CommandType.StoredProcedure;
        sqlcmd.CommandText = strSQL;

        int Result = sqlcmd.ExecuteNonQuery();
        return Result;
    }
    catch (Exception ex)
    {
        throw ex;
    }
    finally
    {
        con.Close();
    }
}

2 个答案:

答案 0 :(得分:3)

不是将strSQL作为CommandText传递,而strSQL是您在第一个代码块中创建的字符串(我认为......),只需将SP名称作为CommandText传递,然后将参数添加到sqlcmd对象。

SqlParameter p = new SqlParameter("@ParameterName", parametervalue));
sqlcmd.Parameters.Add(p);

答案 1 :(得分:0)

只是为了尝试解决您的问题,但请注意,此方法非常危险,并且不推荐用于Sql Injection问题。

string Query_string = "EXEC SP_InsertOffer_Tab @offer_name ='" + 
            this.offer_name +"',  @offer_price = " + 
            this.offer_price + ",@start_date = '" + 
            this.start_date + "',@end_date = '" + this.end_date + "'";

并将CommandType更改为Text。

更好的方法是更改​​Insert_Query方法

public int Insert_Query(string strSQL, SqlParameter[] prm)
{
    using(SqlConnection con = OpenConnection())
    {
        sqlcmd = new SqlCommand(strSql, con);
        sqlcmd.CommandType = CommandType.StoredProcedure;
        sqlcmd.Parameters.AddRange(prm)
        int Result = sqlcmd.ExecuteNonQuery();
        return Result;
    }
}

然后以这种方式调用它

SqlParameter[] prms = new SqlParameter[]
{
   new SqlParameter("@offer_name", SqlDbType.NVarChar),
   new SqlParameter("@offer_price", SqlDbType.Money),
   new SqlParameter("@start_date", SqlDbType.SmallDateTime),
   new SqlParameter("@end_date", SqlDbType.SmallDateTime)
};
prms[0].Value = this.offer_name;
prms[1].Value = this.offer_price;
prms[2].Value = this.start_date;
prms[3].Value = this.end_date;
int result = DbAcess.Insert_Query(Query_string, prms);