用户登录
用户注册

分享至

SQL Server - 比较存储为字符串或 nvarchar 的日期或日期时间?

  • 作者: 段友530234
  • 来源: 51数据库
  • 2023-02-07

问题描述

我按照日期时间格式做了一个日期.但是,我将其作为字符串/nvarchar 而不是日期时间存储在我的数据库中.我能比较这些日期吗?这是一种不好的做法吗?

I made a date according to the datetime format. But, I stored this in my DB as a string/nvarchar and not a datetime. Will I be able to compare such dates ? Is this a bad practice ?

我现在使用 nvarchar 来存储日期时间.

I am using nvarchar to store a datetime as of now.

推荐答案

是的,您仍然可以比较它们,但这肯定是一个不好的做法,因为您需要将此字符串转换为日期数据类型才能进行比较它们之间.如果您在列上定义了索引,则它们将不再使用,因为该列将被转换,并且会导致大型数据库的性能下降.

Yes you can still be able to compare them but this is certainly a bad practice because you will need to convert this strings into dates data type to be able to compare between them. If you have indexes define on the column, they will not be used anymore since the column will be converted and it will cuase slow performance on large database.

比较日期的例子是这样的:

An example on comparing dates is like this:

SELECT *
FROM   tableName
WHERE  CONVERT(DATETIME, dateSTRColumn, XXX) > GETDATE()

其中 XXX 是存储为字符串的日期的当前格式.

where XXX is the current format of the date stored as string.

软件
前端设计
程序设计
Java相关