2

Im having a table called transaktions where i inserted customers billings and customer number. My primary key is an int id that has identity specifikation. My question is how do i select all rows that contains a specific customer_nr and returns all the results?

Right now im doing:

public string getCustomerTransaktions(string CustNr)
{
    using (var cmd = new SqlCommand("select billing_name from [transaktions] where customer_nr = @customer_nr", Connect()))
    {
        cmd.Parameters.AddWithValue("@customer_nr", custNr);
        using (var er = cmd.ExecuteReader())
        {
            if (er.Read())
            {
                return (string)er["billing_name"];
            }
        }
    }
    return "UNKNOWN";
}

This will only print the first row that matches the customer nr, there are atleast 20 rows left. Anyone have any suggestion that will help me? Best Regards

1
  • 1
    It seems you lack some basics... Read the answers below which are perfect to guide you. Commented Apr 18, 2011 at 10:02

4 Answers 4

4

Agree both with @Niklas and @Skurmedel, you need to both use a loop for processing multiple records and collate them together before returning them as a result.

e.g.

public List<string> getCustomerTransaktions(string CustNr)
{
    List<string> names = new List<string>();

    using (var cmd = new SqlCommand("select billing_name from [transaktions] where customer_nr = @customer_nr", Connect()))
    {
        cmd.Parameters.AddWithValue("@customer_nr", custNr);
        using (var er = cmd.ExecuteReader())
        {
            while(er.Read())
            {
                names.Add((string)er["billing_name"]);
            }
        }
    }

    return names;
}
Sign up to request clarification or add additional context in comments.

Comments

3

Since you do return ... and your method specification pretty much limits the results to one particular value, you can never return more than one billing name. It will return a name as soon as a row has been read, or your default if no rows were returned.

You should put the values in a list or likewise and return that.

Comments

2

try to change the if to a while

while (er.Read())

2 Comments

Tried that. The results are the same, only prints the first row
But return in while body, effectively breaks that while.
1

I guesss a simple solution would be to return the whole ResultSet instead of tring to work around with string. Then iterate through its all items from your calling method

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.