在 SQL 查询字符串的 WHERE 语句中插入一个变量日期

Interpolate a variable date in WHERE statement of SQL Query string

我正在使用 .NET Web API2 开发 API。其中一个端点接收一个日期作为参数,它需要 return 一个取决于该日期的项目列表。问题是我无法在 SQL 查询中插入此日期。

假设我需要这个查询作为结果,如果我硬编码日期它就可以工作

Select platform_code, platform_state, COUNT(*) AS 'total cycle', MIN(events.created_at) AS 'first reading'
from events LEFT JOIN platforms ON platforms.platform_code = events.platform_code
WHERE events.created_at BETWEEN '22/06/2020 0:00:00' AND getdate() 
group by platform_code, platform_state

这是我的控制器代码:

{
    [RoutePrefix("api/queries")]
    public class QueriesController : ApiController
    {
        [Route("dashboard")]
        public HttpResponseMessage GetDashboard(string start_date = null)
        {
           DateTime parsed_start_date ;

            using (var ctx = new RFID_TESTEntities())
            {
                if (start_date != null)
                {
                     parsed_start_date = DateTime.ParseExact(start_date, "dd-MM-yyyy", new CultureInfo("es-ES"));

                }
                else
                {
                    parsed_start_date = DateTime.ParseExact("01-01-2020", "dd-MM-yyyy", new CultureInfo("es-ES"));
                }

                String query = "Select platform_code, platform_state, COUNT(*) AS 'total cycle', MIN(events.created_at) AS 'first reading'
                from events LEFT JOIN platforms ON platforms.platform_code = events.platform_code
                WHERE events.created_at BETWEEN " + parsed_start_date + "  AND getdate() 
                group by platform_code, platform_state";
                var platforms = ctx
                    .Database.SqlQuery<Dashboard>(query)
                    .ToList();

如果我尝试 运行 这个,where 子句中的 parsed_start_date 变量缺少单引号,因此我得到一个 SQL 语法错误:

"Select platform_code, platform_state, COUNT(*) AS 'total cycle', MIN(events.created_at) AS 'first reading' from events LEFT JOIN platforms ON platforms.platform_code = events.platform_code
WHERE events.created_at BETWEEN 01/01/2020 0:00:00 AND getdate() 
group by platform_code, platform_state"

在查询中使用它之前,我曾尝试将变量转换为字符串,但显然它的行为方式相同。

您可以在字符串中插入日期并在其中添加单引号

$"'{parsed_start_date}'"

以防万一有人发现它有用,这终于对我有用了,使用 sql 参数,正如评论所说,在安全性方面比我首先尝试做的要好得多:

 String query = "Select platform_code, platform_state, COUNT(*) AS 'total cycle', MIN(events.created_at) AS 'first reading'
                from events LEFT JOIN platforms ON platforms.platform_code = events.platform_code
                WHERE events.created_at BETWEEN @start_date  AND getdate() 
                group by platform_code, platform_state";
                var platforms = ctx
                    .Database.SqlQuery<Dashboard>(query, , new SqlParameter("@start_date", parsed_start_date))
                    .ToList();