简体   繁体   English

SQL Server将日期时间与Char比较

[英]SQL Server Compare Datetime with Char

I am going over a legacy system where a "date" column report_date in a table t_results is set up as char(25). 我正在研究一个遗留系统,在该系统中,表t_results中的“日期”列report_date设置为char(25)。

Name of the column is report_date and it type is report_date (char(25),null) 列的名称为report_date,其类型为report_date (char(25),null)

A sproc utilizes the table as 一个存储程序利用该表作为

ALTER PROCEDURE [dbo].[s_report]
(
    @report_date_from DATETIME,
    @report_date_to DATETIME,
)
AS

SET NOCOUNT ON

SELECT * 
FROM 
    t_results
WHERE
    report_date >= @report_date_from AND report_date <= @report_date_to
ORDER BY report_id

When I run this as EXEC s_report '9/4/2018','10/2/2018' it runs good and I get expected result. 当我以EXEC s_report '9/4/2018','10/2/2018'运行它时,它运行良好并且得到了预期的结果。

When I run the query below (which is same as sproc), I get no results. 当我运行下面的查询(与sproc相同)时,没有任何结果。

SELECT * 
FROM 
    t_results
WHERE
    report_date >= '09/04/2018' AND report_date <= '10/2/2018'

I am not sure how the sproc is working. 我不确定存储过程如何工作。 Any idea or pointers as to how I compare char with datetime in my where clause? 关于如何在where子句中比较char和datetime的任何想法或指针?

Your stored procedure is making a conversion to DateTime. 您的存储过程正在转换为DateTime。 When one of the types is different, SQL Server is doing an implicit conversion when it is making the check thus the SP code is implicitly like: 当其中一种类型不同时,SQL Server在进行检查时将进行隐式转换,因此SP代码是隐式的,如:

where cast(report_date as datetime) >= '09/04/2018' and cast(report_date as datetime) <= '10/2/2018'

Note: Passing a date string like that is not safe and server settings dependent. 注意:传递这样的日期字符串并不安全,并且取决于服务器设置。 Pass like '20180904' and '20181002'. 通过类似``20180904''和``20181002''。

I think your proc essentially does this: 我认为您的proc本质上是这样做的:

SELECT * 
FROM t_results
WHERE report_date >= CAST ('09/04/2018' AS DATETIME) 
  AND report_date <= CAST ('10/2/2018' AS DATETIME) 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM