【发布时间】: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