我试图根据当前日期获取数据 [英] Im trying to fetch data according to current date

查看:72
本文介绍了我试图根据当前日期获取数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

获取错误')'附近的语法不正确。



我尝试过:



 con.Open(); 


SqlCommand cmd1 = new SqlCommand(SELECT [Description] FROM [tbl_Announcements]其中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();

解决方案

一些事情。

1)你没有使用你在查询中创建的参数,为什么要创建它?

2)你错过了那个SQL中的一个小括号。

3)如果你试图使用参数,它将失败 - 假设你的列 ValidityDate 是DATE,DATETIME或DATETIME2字段,因为字符串yyyy / MM / d d hh:MM:tt:ss不是有效日期。 2018/10/03 10:40:33是,但yyyy / MM / dd hh:MM:tt:ss不是。因此SQL会抛出异常...

4) GetDate 函数返回服务器上的当前日期和时间 - 可能没有任何内容如何处理计算机上的日期,取决于PC的位置以及PC的设置方式。只有当您的 ValidityDate 列被插入并且在 GetDate 方面更新为一致时,您才应该使用它。

我建议的是:

  string  sql =   SELECT说明FROM tbl_Announcements其中Active = 1 AND ValidityDate> = @ValidityDate; 
使用(SqlCommand cmd1 = new SqlCommand(sql,con))
{
cmd1.Parameters.AddWithValue( @ ValidityDate,DateTime.Now.Date);
使用(SqlDataReader dr1 = cmd1.ExecuteReader())
{
...


getting error Incorrect syntax near ')'.

What I have tried:

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();

解决方案

Couple of things.
1) You don't use the parameter you create in your query, so why are you creating it at all?
2) You are missng a close bracket in that SQL.
3) If you try to use the parameter, it will fail - assuming your column ValidityDate is a DATE, DATETIME, or DATETIME2 field, because the string "yyyy/MM/dd hh:MM:tt:ss" is not a valid date. "2018/10/03 10:40:33" is, but "yyyy/MM/dd hh:MM:tt:ss" isn't. So SQL would throw an exception...
4) The GetDate function returns the current date and time on the server - which may have nothing to do with the date on your computer, it depends on where the PC is, and how it was configured when it was set up. You should only use it if your ValidityDate column was INSERTed and UPDATEed in terms of GetDate to be consistent.
What I'd suggest is this:

string sql = "SELECT Description FROM tbl_Announcements where Active = 1 AND ValidityDate >= @ValidityDate";
using (SqlCommand cmd1 = new SqlCommand(sql, con))
    {
    cmd1.Parameters.AddWithValue("@ValidityDate", DateTime.Now.Date);
    using (SqlDataReader dr1 = cmd1.ExecuteReader())
        {
        ...


这篇关于我试图根据当前日期获取数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆