【问题标题】:Convert string to datetime in where statement in SQL Server在 SQL Server 中的 where 语句中将字符串转换为日期时间
【发布时间】:2012-05-23 11:53:02
【问题描述】:

我在 SQL Server 2005 中将字符串转换为 datetime 时遇到问题。

如果在这样的 where 语句中使用 Convert(datetime, x)

SELECT ThumbId
FROM [ImageBankSQL].[dbo].[MetaData]
WHERE (DataKey = 'ImagePropertyTagExifDTOrig'
       OR DataKey='ImagePropertyTagDateTime')
AND CONVERT(datetime, DataValue, 120) > CONVERT(datetime, '2011-09-23 00:00:00', 120)

我明白了:

从字符串转换日期时间时转换失败

但是,如果我选择转换后的 datetime 而不是在 where 语句中使用它们,一切都很好,并且我得到了转换后的日期:

SELECT ThumbId, Convert(datetime, DataValue, 120), Convert(datetime, '2011-09-23 00:00:00', 120)
FROM [ImageBankSQL].[dbo].[MetaData]
WHERE (DataKey = 'ImagePropertyTagExifDTOrig'
       OR DataKey = 'ImagePropertyTagDateTime')

在这两个示例中,我都使用了Convert(datetime, DataValue, 120)Convert(datetime, DataValue),结果相同。

为什么我可以在选择中转换,但不能在哪里转换?以及如何在 where 语句中使用 convert 进行第一个查询?

【问题讨论】:

标签: sql-server-2005 datetime type-conversion


【解决方案1】:

当您进行选择时,转换仅适用于满足您条件的 DataValue(即 DataKey = 'ImagePRpertyTagDateTime')

SQL Server 不执行惰性求值,因此使用 where 子句中的 Convert,它将针对所有行求值,即使 DataValue 不适合解析为日期。

【讨论】:

    猜你喜欢
    • 2019-08-31
    • 2021-06-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多