問題描述
我只想驗證來自用戶的給定輸入
I just want to validate a given input from the user
Declare @UserInput NVARCHAR(20)
set @UserInput = '26/07/2013'
select ISDATE(@UserInput)
這將返回 false,因為日期是澳大利亞格式,即使日期有效
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))
它的工作原理.但是如果@Userinput 是垃圾(即:- 'hello'),那么最后一條語句就會失敗.我怎樣才能擁有一些東西,無論用戶輸入什么,它都會將其驗證為澳大利亞日期 (dd/mm/yyyy)?
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)?
謝謝
推薦答案
使用 SET DATEFORMAT 指定您希望輸入的日期格式:
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)
我傾向于在輸入到達 SQL-Server 之前執行此類驗證,并確保任何日期變量都是日期.
I would be inclined to perform such validations prior to the input reaching SQL-Server, and ensuring that any date variables are dates.
這篇關于在 t-sql 中驗證日期?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!