将日期与SQL Server中的日期进行比较

时间:2022-03-04 10:08:18

I am facing this problem where SQL asked me to put aliases when I'm converting chars to date format, here is my query:

我正面临这个问题,当我将字符转换为日期格式时,SQL要求我输入别名,这是我的查询:

declare @dateTarget char(8) = '20130613'
declare @dateTarget2 char(8) = '20180608'
declare @dateNow as date = GETDATE()

IF CAST(CONVERT(DATE, 
                LEFT(@dateTarget, 4) + SUBSTRING(@dateTarget, 5, 2) + RIGHT(@dateTarget, 2))) >= CAST(@dateNow AS DATE) 
BEGIN
    PRINT 'Target cannot be greater than DateNow.'
END
ELSE IF CAST(CONVERT(DATE, LEFT(@dateTarget2, 4) + SUBSTRING(@dateTarget2, 5, 2) + RIGHT(@dateTarget2, 2))) >= CAST(@dateNow AS DATE) 
BEGIN
    PRINT 'Target2 cannot be greater than DateNow.'
END
ELSE
BEGIN
    PRINT 'ok'
END

and these are the errors I get:

这些是我得到的错误:

Msg 1035, Level 15, State 10, Line 5
Incorrect syntax near 'CAST', expected 'AS'.

Msg 1035,Level 15,State 10,Line 5'CAST'附近的语法不正确,预期为'AS'。

Msg 156, Level 15, State 1, Line 9
Incorrect syntax near the keyword 'ELSE'.

Msg 156,Level 15,State 1,Line 9关键字'ELSE'附近的语法不正确。

Msg 1035, Level 15, State 10, Line 9
Incorrect syntax near 'CAST', expected 'AS'.

消息1035,级别15,状态10,行9''CAST'附近的语法不正确,预期为'AS'。

Msg 156, Level 15, State 1, Line 13
Incorrect syntax near the keyword 'ELSE'.

消息156,级别15,状态1,行13关键字“ELSE”附近的语法不正确。

1 个解决方案

#1


3  

If you want to convert string to date use Cast or Convert

如果要将字符串转换为日期,请使用Cast或Convert

select CAST(@dateTarget as date) 
select CONVERT(date, @dateTarget)

SQL Server can implicitly convert your string to date (though I recommend an explicit conversion)

SQL Server可以隐式地将您的字符串转换为日期(尽管我建议进行显式转换)

declare @dateTarget  char(8) = '20130613'
declare @dateTarget2  char(8) = '20180608'
declare @dateNow as date = GETDATE()

IF @dateTarget >= @dateNow
BEGIN
    print 'Target cannot be greater than DateNow.'
END
ELSE IF @dateTarget2 >= @dateNow
BEGIN
    print 'Target2 cannot be greater than DateNow.'
END
ELSE
BEGIN
    print 'ok'
END

#1


3  

If you want to convert string to date use Cast or Convert

如果要将字符串转换为日期,请使用Cast或Convert

select CAST(@dateTarget as date) 
select CONVERT(date, @dateTarget)

SQL Server can implicitly convert your string to date (though I recommend an explicit conversion)

SQL Server可以隐式地将您的字符串转换为日期(尽管我建议进行显式转换)

declare @dateTarget  char(8) = '20130613'
declare @dateTarget2  char(8) = '20180608'
declare @dateNow as date = GETDATE()

IF @dateTarget >= @dateNow
BEGIN
    print 'Target cannot be greater than DateNow.'
END
ELSE IF @dateTarget2 >= @dateNow
BEGIN
    print 'Target2 cannot be greater than DateNow.'
END
ELSE
BEGIN
    print 'ok'
END