简体   繁体   中英

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.

I get one date parameter as string in 'dd-MM-yyyy' format.

@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 .

You need to use CAST() function to convert to date format.

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.

Since you're on SQL Server 2016 , you could use the PARSE function and define the culture needed to successfully parse this string.

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 ).

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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