【问题标题】:Using Date Difference to return value with datetime in an sqlserver from today to 7 days ago从今天到 7 天前,使用日期差异在 sqlserver 中返回带有日期时间的值
【发布时间】:2015-05-08 07:21:57
【问题描述】:

基本上,我正在做一个连接到 sql 的项目,并且我必须只返回两列(tablein 和 tableout)中具有 null 的值。我需要在运行该程序时执行此操作,它会检查今天的日期并返回 7 天,并从过去 7 天开始检查是否有空值。它从 tabledate 列进行检查。现在我设法连接到数据库并显示空值,但我正在显示具有空值的整个列表。现在我尝试使用日期差异从今天返回 7 天,方法是输入一个 Sql 命令,如下面的代码所示。这没有用,我一直在浏览互联网,但没有关于我需要什么的信息出现,我希望是否有人知道他们是否可以帮助我。非常感激。代码如下。

using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace sql_connection
{
class Program
   {
static void Main(string[]args)
{

     DateTime oldDate= DateTime.Now.AddDays(-7);
     DateTime newDate = DateTime.Now;

     TimeSpan ts= newDate-oldDate;
     int diffferenceInDays = ts.Days;

    string conn=null;
    SqlConnection connection;
    conn=("Data Source=Database\\SQL2012;Initial Catalog=Table;User ID=user;Password=example");

    connection=new SqlConnection(conn);

    try{

        connection.Open();
        Console.Writeline("Connection Open!");
        SqlCommand cmd= new SqlCommand("SELECT tabledate, tablein,tableout,tableuser FROM [dbo].[tb_Showingnull]"WHERE DATEADD(dd,-7,GETDATE()) FROM tabledate AND tablein AND tableout IS NULL);
        cmd.Connection = connection;
        SqlDataReader reader = cmd.ExecuteReader();
        while(reader.Read())
        {

            Console.WriteLine("{2}, {1} , {0}", reader["tablein"] == DBNull.Value? "NULL" : reader["tablein"].ToString(), reader["tableout"] == DBNull.Value? "NULL" : reader["tableout"].ToString(), reader["tableuser"].ToString(), reader["tabledate"].ToString();

        }

        connection.Close();
    }

    catch(Exception ex)
    {
       Console.WriteLine(ex.Message);
    }

    }
}

}

【问题讨论】:

  • 什么不起作用?我没看到你在哪里使用DATEDIFF
  • @TimSchmelter 在 sql 命令中,在我放置 tabledate 之后的位置是 differenceinDays。
  • 看你的问题,我可以看出它的堆栈溢出驱动开发(SODD)——你自己付出了零努力,当你得到以前的答案时,继续问新问题
  • 你的规则不清楚。这是什么意思:WHERE tabledate is differenceinDays tablein AND tableout IS NULL

标签: c# datediff


【解决方案1】:

您的 SqlCommand 查询看起来错误。双引号中似乎缺少 WHERE 子句。我认为它应该看起来像这样:

SqlCommand cmd= new SqlCommand("SELECT tabledate, tablein,tableout,tableuser FROM [dbo].[tb_Showingnull] WHERE tabledate = DateAdd(DD," + differenceinDays + ",GETDATE()) AND tablein IS NULL AND tableout IS NULL");

您还应该注意,您还需要指定 'tablein' 是否也应为 NULL。写“tablein AND tableout IS NULL”将无法过滤它们都为空。它需要是 'tablein IS NULL AND tableout IS NULL'。

【讨论】:

  • '>' 附近的语法不正确,这很有趣,因为我没有把它放在我的编码中。
  • @bobby - 该代码中没有“>”字符。你确定你没有以某种方式放入一个?在 SSMS 中尝试您的查询,看看它是否有效。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-10-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多