Search code examples
c#sqlsql-server-ce

Select more columns with MAX function in SQLCE


Need to find max value of id, and by this value I need to read value of others column. But it is influenced by another column type. I used this sql command:

"SELECT * FROM Table WHERE id = (SELECT MAX(id) FROM Table WHERE type = 1)"

ID column is bigint type, and type is nchar. I tried use it with type = '1' too, but same problem. Error is after "id = " section

Thanks for reply

EDIT:

SqlCeCommand com = new SqlCeCommand();
if (LocalType == '1') { com = new SqlCeCommand("SELECT req_id FROM Requisition WHERE id = (SELECT MAX(id) FROM Requisition WHERE type = 1)", con); }
else if (LocalType == '2') { com = new SqlCeCommand("SELECT req_id FROM Requisition WHERE id = (SELECT MAX(b.id) FROM Requisition AS b WHERE b.type <> 1)", con); }

using (com)
{
   SqlCeDataReader reader = com.ExecuteReader();
}

Solution

  • The easiest way to do this is using top. If this is your real code, then you need to "escape" the word "table" because it is a reserved word:

    select top 1 t.*
    from [table] t
    where type = '1'
    order by id desc