与带有日期时间字符串的查询连接字符串

本文关键字:字符串 连接 查询 时间 日期 | 更新日期: 2023-09-27 18:14:09

我无法手动添加CurrentSystemTime到我的查询。查询存储在一个字符串变量中。但是连接部分给出错误:

查询是:

string myQuery= @"SELECT MAX(ASD.eventDateTime) AS second, R.resourceID,R.resourceLoginID,ASD.agentID
                  FROM AgentStateDetail AS ASD INNER JOIN 
                  Resource AS R ON ASD.agentID = R.ResourceID WHERE ASD.eventDateTime >='" + DateTime.Today.ToString("yyyy-MM-dd h:mm:ss") + "'AND ASD.eventDateTime <='2016-10-18 23:59:59' 
                  GROUP BY R.ResourceID,R.resourceLoginID,ASD.agentID"

问题部分是:

ASD。eventDateTime>='" +DateTime.Today。ToString("yyyy-MM-dd h:mm:ss") + "'

错误是:

将文本表示为常量中的unicode字符换行符。

与带有日期时间字符串的查询连接字符串

您忘记以@开始字符串的第二部分,这就是编译器修改换行符无效的原因:

string myQuery= @"SELECT MAX(ASD.eventDateTime) AS second, R.resourceID,R.resourceLoginID,ASD.agentID
                  FROM AgentStateDetail AS ASD INNER JOIN 
                  Resource AS R ON ASD.agentID = R.ResourceID WHERE ASD.eventDateTime >='" + DateTime.Today.ToString("yyyy-MM-dd h:mm:ss") + @"'AND ASD.eventDateTime <='2016-10-18 23:59:59' 
                  GROUP BY R.ResourceID,R.resourceLoginID,ASD.agentID"

您可以像下面这样使用参数化查询,

string sql = "SELECT MAX(ASD.eventDateTime) AS second, R.resourceID, R.resourceLoginID, ASD.agentID FROM AgentStateDetail AS ASD INNER JOIN Resource AS R ON ASD.agentID = R.ResourceID WHERE ASD.eventDateTime >= @dateTimeStart AND ASD.eventDateTime <= @dateTimeEnd GROUP BY R.ResourceID,R.resourceLoginID,ASD.agentID";
using (SqlConnection connection = new SqlConnection(/* connection info */))
using (SqlCommand command = new SqlCommand(sql, connection))
{
    var dateTimeStart = new SqlParameter("dateTimeStart", SqlDbType.DateTime);
    dateTimeStart.Value = new DateTime("yyyy-MM-dd h:mm:ss");
    var dateTimeEnd = new SqlParameter("dateTimeEnd", SqlDbType.DateTime);
    dateTimeEnd.Value = new DateTime("yyyy-MM-dd h:mm:ss");
    command.Parameters.Add(dateTimeStart);
    command.Parameters.Add(dateTimeEnd);
    var results = command.ExecuteReader();
}