简体   繁体   中英

Can we use return rdr using a stored procedure in C#?

I have table as follows

emp_id, emp_name, emp_address, emp_salary, emp_rating

I would like to get all the above rows ... I have written stored procedure as follows:

CREATE PROCEDURE [dbo].[fetch_empdata]
@empid int
AS
SELECT * 
FROM emptable
WHERE emp_id = @empid;
string connection = "Data Source=" + server + ";Initial Catalog=" + dbase + ";User ID=" + userid + ";Password=" + password;

conn = new SqlConnection(connection);
conn.Open();
SqlCommand cmd  = new SqlCommand(storedprocedure, conn);

cmd.CommandType = CommandType.StoredProcedure;

cmd.Parameters.Add(new SqlParameter("@empid", empid));

rdr = cmd.ExecuteReader();

Is there a way to use a command return rdr? I would like to return all the values of this table to some other class. Or do I have to explicitly move var empid = rdr("EMPID")?

according to msdn you are doing it right, if you are setting your variable storedprocedure to the value "fetch_empdata"

Then, to get the value, you could do

if(rdr.Read()) {
    string emp_id = rdr.GetString(0);
}

being 0 the index of your "EMPID" column

EDIT: A good thing to keep in mind is the fact that you are using SELECT * to retrieve data, which is not a good practice, as any change in the table columns will result in a change in the select return, and could also break your application.

A good approach would be to explicitly inform which columns you want to return, and the order of them, such as

SELECT EMPID, EMPNAME, ...

Once you get your SqlDataReader like this:

rdr = cmd.ExecuteReader();

you now need to enumerate over the result set:

while(rdr.Read())
{
    int emp_id = rdr.GetInt(0);
    string emp_name = rdr.GetString(1);
    string emp_address = rdr.GetString(2);
    decimal emp_salary = rdr.GetDecimal(3);
    int emp_rating = rdr.GetInt(4);

    // do something with those variables.... then move on to next row
}

What you do with those variables is entirely up to you - whatever makes sense for you. Stick them into an object and put all objects retrieved into a List<Employee> or something - whatever you want.

Also: you might need to check for NULL values, too - before calling .GetString/.GetInt etc. - otherwise you'll get an exception.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM