validate a date in t-sql?

两盒软妹~` 提交于 2019-12-22 10:44:09

问题


I just want to validate a given input from the user

Declare @UserInput NVARCHAR(20)
set @UserInput = '26/07/2013'
select ISDATE(@UserInput)

This will return false as the date is in australian format, even though the date is valid

I can change the last line to the folowing

select isdate(CONVERT(datetime, @UserInput, 103))

and it works. But if the @Userinput was rubbish (ie:- 'hello'), then the last statement would fail. How can I have something, where no matter what the user enters, it validates it to an australian date (dd/mm/yyyy)?

Thanks


回答1:


Use SET DATEFORMAT to specify the format you are expecting the date to be entered in:

SET DATEFORMAT DMY;

Declare @UserInput NVARCHAR(20)
set @UserInput = '26/07/2013'
select ISDATE(@UserInput)

I would be inclined to perform such validations prior to the input reaching SQL-Server, and ensuring that any date variables are dates.




回答2:


Assuming that you are using SQL Server 2012 and above, you could use TRY_CONVERT instead:

select isdate(TRY_CONVERT(datetime, @UserInput, 103))



来源:https://stackoverflow.com/questions/19094315/validate-a-date-in-t-sql

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!