简体   繁体   English

从字符串到日期时间的SQL Server日期比较

[英]SQL Server Date Comparison from string to datetime

I am using a SQL Server 2016 database and in my stored procedure I want to compare two dates. 我正在使用SQL Server 2016数据库,在我的存储过程中,我想比较两个日期。

I get one date parameter as string in 'dd-MM-yyyy' format. 我以“dd-MM-yyyy”格式将一个日期参数作为字符串。

@stringdate = '28-12-1990'   // I get date in this format

I want to convert this to date format and compare with a database column which is of type datetime . 我想将其转换为日期格式,并与datetime类型的数据库列进行比较。

You need to use CAST() function to convert to date format. 您需要使用CAST()函数转换为日期格式。

Try this Code: 试试这个代码:

CAST(dbdatetimecolumnname AS date) = (CAST(RIGHT(@stringdate,4) + '-' + LEFT(RIGHT(@stringdate,7),2) + '-' + LEFT(@stringdate,2) AS DATE))

Right() & Left() functions are used rearrange your string date format to db date format. 使用Right()Left()函数将字符串日期格式重新排列为db日期格式。

Since you're on SQL Server 2016 , you could use the PARSE function and define the culture needed to successfully parse this string. 由于您使用的是SQL Server 2016 ,因此可以使用PARSE函数并定义成功解析此字符串所需的区域性。

Something like 就像是

DECLARE @stringdate VARCHAR(20) = '28-12-1990';
DECLARE @parseddate DATETIME2(3);

SELECT @parseddate = PARSE(@stringdate AS DATE USING 'de');
SELECT @parseddate

I used the de culture for Germany - since the format of the date you have is a European format ( dd-MM-yyyy ). 我在德国使用了de文化 - 因为你所拥有的日期格式是欧洲格式( dd-MM-yyyy )。

Check this: 检查一下:

set dateformat dmy
declare @d datetime='31-01-2016'
select @d
go


set dateformat ymd

declare @d datetime='31-01-2016'
select @d
go

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

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