[英]Converting varchar column to Date in sql
I am using MSSQL server.我正在使用 MSSQL 服务器。 I have a column named logDate which is of varchar type.我有一个名为 logDate 的列,它是 varchar 类型的。
I have to perform operation like ' I have to delete the records which are older than 10 days '.我必须执行“我必须删除超过 10 天的记录”之类的操作。
Which query i can use to perform this operation?我可以使用哪个查询来执行此操作?
How to convert the varchar to Date type?如何将 varchar 转换为 Date 类型?
Here logDate varchar is in the format ddmmyyyy这里 logDate varchar 的格式为 ddmmyyyy
I searched i got few links but i am not able to perform this operation.我搜索了几个链接,但我无法执行此操作。
Thanks for your time:)谢谢你的时间:)
You would use delete
.您将使用delete
。 The trick is converting logdate
to a real date:诀窍是将logdate
转换为真实日期:
delete t
where datefromparts(right(logdate, 4), substring(logdate, 3, 2), left(logdate, 2)) < dateadd(day, -10, convert(date, getdate()));
This deconstructs the MMDDYYYY format into the year, the month, and the date and then constructs a date from those components.这会将 MMDDYYYY 格式解构为年、月和日期,然后从这些组件构造日期。
Note: This assumes that you don't actually care about the specific time.注意:这假设您实际上并不关心具体时间。
Another way to convert the times uses string conversions:另一种转换时间的方法是使用字符串转换:
where convert(date, right(logdate, 4) + left(logdate, 4)) < dateadd(day, -10, convert(date, getdate())
This restructures the string as YYYYMMDD, which is a standard format that is readily converted from a string to a date.这会将字符串重组为 YYYYMMDD,这是一种标准格式,可以很容易地从字符串转换为日期。
if you want to simply convert this to date:如果您想简单地将其转换为日期:
declare @date nvarchar(max) = '12032020'
select cast(substring(@date, 5, 4)+substring(@date, 3, 2)+substring(@date, 1, 2) AS date)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.