Sybase (T-SQL) 中 varchar 日期验证的最佳方法?
我有一个存储过程,它采用 varchar 作为参数,需要将其转换为 datetime 供以后使用:
SET @the_date = CAST(@date_string AS DATETIME)
我希望在格式为“DD-MON-YYYY”,但为了防御性编码,如果由于某种原因无法成功转换,我想默认为系统日期并继续。 在 PL/SQL 中,我可以使用异常处理来实现这一点,而且我也可以使用正则表达式相当轻松地做到这一点,但是 Sybase 支持的开箱即用的有限模式匹配不允许我这样做,而且我不能依赖第三方库或扩展。 在 T-SQL 中是否有一种简单的方法可以做到这一点?
注意:使用Sybase ASE 12.5.3,没有ISDATE功能
I have a stored procedure which takes as its parameter a varchar which needs to be cast as a datetime for later use:
SET @the_date = CAST(@date_string AS DATETIME)
I'm expecting the date string to be supplied in the format "DD-MON-YYYY", but in an effort to code defensively, if for some reason it can't be cast successfully, I want to default to the system date and continue. In PL/SQL I could use exception handling to achieve this and I could do this fairly easily with regular expressions too, but the limited pattern matching supported out of the box by Sybase doesn't let me do this and I can't rely on third party libraries or extensions. Is there a simple way of doing this in T-SQL?
NB: using Sybase ASE 12.5.3, there is no ISDATE function
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
我有类似的问题。 您也许可以执行以下操作:
但是,这在选择中效果不佳。 它在游标 (boo) 或 SQL 批处理之前/之后的逻辑中运行良好。
I'm having a similar issue. You might be able to do something like this:
However, this doesn't work well in a select. It will work well in a cursor (boo) or in logic before / after a SQL batch.
天哪,如果问题是关于 Microsoft SQL Server 的,那么我们就已经开始做生意了!
遗憾的是,自 1997 年左右(事实上,大约一年左右)以来,Sybase 现在已经完全是另一个数据库了。
如果输入格式只需为“DD-MON-YYYY”并且没有例外,那么我认为在首先执行一些简单的操作(例如检查长度)之后,通过使用 SUBSTR() 对输入进行切片来实现相当多的验证。
不过,我认为 Sybase 的最新版本(例如 SQL Anywhere 11)具有正则表达式支持,尽管我已经有一段时间不再受 T-SQL 之苦了。 一些谷歌搜索让我更加怀疑。
My goodness, if the question was about Microsoft SQL Server then we'd have been in business!
Sybase, sadly, is a whole 'nother database these days, since about 1997, in fact, give or take a year.
If the input format simply has to be 'DD-MON-YYYY' and no exceptions, then I think a fair amount of validation was be achieved by slicing the input using SUBSTR(), after first doing some simple things, such as checking length.
I thought that recent releases of Sybase (SQL Anywhere 11, for example) have regular expression support, however, although it's been a while since I've had to suffer T-SQL. Some googling leaves me in rather more doubt.
你不能做这样的事情吗:
?
Can't you do something like this:
?
找到这是 Google 搜索“验证日期字符串 sql”时的第二个结果。
Found this in the second result in Google when searching for "validate date string sql".
通过执行以下命令,确保 SQL Server 知道字符串中日、月和年的顺序
Make sure SQL Server knows the order of Days, Months and Years in your string by executing
您是否尝试过
convert
而不是cast
?Did you try
convert
instead ofcast
?