Search code examples
c#stored-proceduresidatareader

using IDataReader to call store procedure with parameters


I use IDataReader to call stored procedures without parameters. I am not finding examples of how to do this when parameters are present. Does IDataReader handle parameters of stored procedure?

Please provide an example.


Solution

  • If you're using the Enterprise Library, this style will work well for you:

    using System;
    using System.Collections.Generic;
    using System.Data;
    using System.Data.Common;
    using System.Data.SqlClient;
    using System.Text;
    using Microsoft.Practices.EnterpriseLibrary.Data.Sql;
    
    // ...
    
    SqlDatabase db = new SqlDatabase("YourConnectionString");
    DbCommand cmd = db.GetStoredProcCommand("YourProcName");
    cmd.Parameters.Add(new SqlParameter("YourParamName", "param value"));
    
    using (IDataReader dr = db.ExecuteReader(cmd))
    {
        while (dr.Read())
        {
            // do something with the data
        }
    }