locked
trying to fetch data according to date but getting exception Incorrect syntax near ')'. RRS feed

  • Question

  • User727611295 posted

    con.Open();
    SqlCommand cmd1 = new SqlCommand("SELECT [Description] FROM [tbl_Announcements] where Active = 1 AND ([ValidityDate] >= GetDate()",con);
    cmd1.Parameters.AddWithValue("@ValidityDate",SqlDbType.NVarChar).Value = Convert.ToString("yyyy/MM/dd hh:MM:tt:ss");
    SqlDataReader dr1 = cmd1.ExecuteReader();
    while (dr1.Read())
    {
    k = dr1["Description"].ToString();

    }
    Label2.Text = k;
    con.Close();

    Wednesday, October 3, 2018 9:58 AM

All replies

  • User753101303 posted

    Hi,

    Try AND [ValidityDate]>= etc... rather than AND ([ValidityDate] 

    This extra parenthesis is opened but never closed (causing it to be paired with the ) parenthesis used by the GETDATE function). IMO don't use parenthesis when they are not needed.

    Also for now you are using GETDATE() rather than a @ValidityDate parameter and the code that populates this parameter seems wrong. IMO it's best to always pass native values (ie for a datetime you'll pass a datetime value rather than a string).

    For example you could start wiht :

    SqlCommand cmd1 = new SqlCommand("SELECT [Description] FROM [tbl_Announcements] where Active = 1 AND [ValidityDate] >= @ValidityDate",con);
    cmd1.Parameters.AddWithValue("@ValidityDate",DateTime.Now);

    Wednesday, October 3, 2018 10:57 AM