Click here to Skip to main content
15,891,683 members
Please Sign up or sign in to vote.
4.00/5 (1 vote)
Hi,

I am having a problem reading data from SQL database.

The syntax is like such:

SELECT Max(Property_ID) FROM Property

I tried it in SQL Server Management Studio Express and it works, but when I tried to execute it in Visual Web Developer..., it gets me an error.


Here the code:

string SelectProperty_ID = "SELECT Max(Property_ID) FROM Property";
        SqlCommand property_id_Command = new SqlCommand(SelectProperty_ID, connect1);
        SqlDataReader readProperty_ID;
        
        try
        {
            connect1.Open();//make connection
            readProperty_ID = property_id_Command.ExecuteReader();
            readProperty_ID.Read();
            lblSpecial.Text = readProperty_ID["Property_ID"].ToString();
            readProperty_ID.Close();
        }
        catch (Exception error) { Label1.Text = "Error Readin.......etc


BTW, having readProperty_ID.Read(); with or without while NO good.

Could anyone help please.
Posted
Updated 26-Jan-10 8:29am
v2

Without digging into this and coding it, I have two suggestions you can try:

1). Use an alias on on the name in your SQL statement
e.g. "SELECT MAX(Property_ID) Property_ID FROM Property"
Most likely, you're getting an error because Property_ID does not actually exist in the reader, since you're using an aggergate function

2). instead of doing ExecuteReader do ExecuteScalar, since you have a single return value, and cast the return OBJECT type into an integer.
 
Share this answer
 
v2
Thanks for your replies.

But, can you please tell me how this,
SELECT MAX(Property_ID) \"Property_ID\" FROM Property

, works in c# code

while in a normal SQL query should be like this
SELECT MAX(Property_ID) "\Property_ID\" FROM Property
 
Share this answer
 
make this change to your code and u will get desired result..
try
        {
            connect1.Open();//make connection
            readProperty_ID = property_id_Command.ExecuteReader();
            while(readProperty_ID.Read())
            {
                lblSpecial.Text = readProperty_ID["Property_ID"].ToString();
            }
       readProperty_ID.Close();
 
       }
        catch (Exception error) { Label1.Text = "Error Readin.......etc


happy coding
 
Share this answer
 
v2
The reason being, in C#, in order to embed quotes in a string, you have to preface the quotes with a forward slash.

String sqlStatement = "SELECT MAX(PROPERTY_ID_MAX) \"PROPERTY_ID_MAX\" FROM PROPERTY"

That translates to

SELECT MAX(PROPERTY_ID_MAX) "PROPERTY_ID_MAX" FROM PROPERTY
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900