0

I have a little problem with selecting max ID from my database. This is my code:

string checkcat = "SELECT MAX(PRODUCT_ID) FROM CMS_PRODUKTY WHERE (CATEGORY_ID = CATEGORY_ID) AND (CLIENT_ID = @CLIENT_ID)";
SqlCommand cmd2 = new SqlCommand(checkcat, con);
cmd2.Parameters.Add("@CATEGORY_ID", System.Data.SqlDbType.Int).Value = kategoria;
cmd2.Parameters.Add("@CLIENT_ID", System.Data.SqlDbType.Int).Value = HiddenField1.Value;
con.Open();
int noweid = Convert.ToInt32(cmd2.ExecuteScalar());
con.Close();

The point is the new int "noweid" should be 1 or higher - depend on product_id inside table, but it's returning 0. I don't have any idea why... The other variables - kategoria and HiddenField1.Value are correct.

Any ideas what did I do wrong?

Ashiv3r
  • 894
  • 4
  • 14
  • 28
  • Have you tried executing this query against the database using SQL Server Management Studio and verifying that it returns 1 or higher there? – Lasse V. Karlsen Sep 28 '15 at 11:44
  • 1
    It won't solve your problem but you have a typo `(CATEGORY_ID = CATEGORY_ID)` should be `(CATEGORY_ID = @CATEGORY_ID)` - note the `@`. – petelids Sep 28 '15 at 11:44

1 Answers1

2

You have

WHERE (CATEGORY_ID = CATEGORY_ID)

but you want

WHERE (CATEGORY_ID = @CATEGORY_ID)

You should also parse the string to int:

cmd2.Parameters.Add("@CLIENT_ID", System.Data.SqlDbType.Int).Value = int.Parse(HiddenField1.Value);

maybe kategoria is also a string, then parse it also to int.

Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939
  • Thanks. It's working perfectly. Have read this code thousand times and didn't see such a mistake... Just needed to add @ to sql condition. – Ashiv3r Sep 28 '15 at 11:47