日期:2014-05-17  浏览次数:20765 次

存储过程实现执行带参数的SQL语句
请问存储过程如何实现执行带参数的SQL语句?

string[] list = 参数集合;
for (int i = 0; i < list.Length; i++)
    {

        result = string.Format("@Param_{0}_{1}",sign, i);//拼接的SQL语句
        ......
        Parameters.Add(
             new SqlParameter(string.Format("@Param_{0}_{1}",sign, i), SqlDbType.NVarChar) { Value = list[i].Trim() }
        );//对应的参数
    }

以前是直接执行SQL,传sql语句,传参数就行了。
现在是把这些SQL语句传到存储过程中进行某些处理后再执行,
存储过程如何接收这样参数?
比如:
拼好的语句

Select * from tempTable where Col1 = @col1 and Col2 = @col2;

 @col1 , @col2我该如何传给存储过程?

还是说,我直接把值赋好。

Select * from tempTable where Col1 = 'col1' and Col2 = 'col2';

这样的话貌似又不安全。

------解决方案--------------------
使用字符串拼接就可以实现,而且很安全
------解决方案--------------------
SqlParameter proid = new SqlParameter("@id", SqlDbType.Int);
            proid.Value = id;
            SqlParameter proFea = new SqlParameter("@feature", SqlDbType.VarChar, -1);
            proFea.Direction = ParameterDirection.Output;
            SqlParameter[] numbers = new SqlParameter[2] { proid, proFea };


            DataSet ds = SqlHelper.ExecuteReaderFill(SqlHelper.ConnectionStringLocalTransaction, CommandType.StoredProcedure, "GetProduct", numbers);


 public static DataSet ExecuteReaderFill(string connectionString, CommandType cmdType, string cmdText, params SqlParameter[] commandParameters)
        {
            SqlCommand cmd = new SqlCommand();
            SqlConnection conn = new SqlConnection(connectionString);

            // 在这里使用try/catch处理是因为如果方法出现异常,则SqlDataReader就不存在,
            //CommandBehavior.CloseConnection的语句就不会执行,触发的异常由catch捕获。
            //关闭数据库连接,并通过throw再次引发捕捉到的异常。
            try
            {
                DataSet ds = new DataSet();
                PrepareCommand(cmd, conn, null, cmdType,&nbs