gpt4 book ai didi

sql - 有没有安全的方法来转换 SQL 日期时间?

转载 作者:行者123 更新时间:2023-12-02 08:53:33 24 4
gpt4 key购买 nike

非常简单的问题,我找不到答案:

是否有一种简单且安全的†方法可以在 SQL Server 中将 varchar 转换为 datetime

† 即使用默认日期时间值优雅地处理非日期时间字符串

最佳答案

您可以使用 isdate 过滤行功能。此查询返回三行,没有任何转换错误:

with v as (
select '20110714' value union all
select '2011-07-15' union all
select '3/22/2011' union all
select 'foo'
)
select cast(value as datetime)
from v
where isdate(value) = 1

编辑

当您想要默认值(例如当前日期/时间)时,您可以执行以下操作:

select case when isdate(value) = 1 then cast(value as datetime) else getdate() end

关于sql - 有没有安全的方法来转换 SQL 日期时间?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6688555/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com