简体   繁体   English

如何使用Tsql在varchar(6)中转换和计算日期时间类型yyyymm

[英]How to convert and calculate datetime type yyyymm in varchar(6) using Tsql

I have 2 columns with datatype varchar(6) like this, format yyyymm . 我有2列数据类型为varchar(6) ,格式为yyyymm Now I want to datediff between them. 现在,我想在他们之间datediff This is my solution, 这是我的解决方案,

select
    tblA, 
    tblB, 
    datediff(month, convert(datetime, tblA+'01', 120),convert(datetime, tblb+'01',120)+1 as count
from mytbl 

any other ideas? 还有其他想法吗? Thanks 谢谢

It turns out that strings of the form YYYYMMDD can be converted directly to date values with no format needed. 事实证明,格式为YYYYMMDD的字符串可以直接转换为日期值,而无需格式。 So, a slightly simpler version is: 因此,一个稍微简单的版本是:

select tblA, tblB, 
       datediff(month, convert(date, tblA + '01'), convert(datetime, tblb+'01')+1 as cnt
from mytbl;

I should note that you could also do: 我应该指出,您可以这样做:

select ( (left(tblA, 4) * 12 + right(tblA, 2)) - 
         (left(tblB, 4) * 12 + right(tblB, 2))
       )

SQL Server will convert the strings to numbers in a numeric context. SQL Server将在数字上下文中将字符串转换为数字。

Also, I find it strange that date columns are called tblA and tblB , but that is how the question is phrased. 此外,我发现将日期列称为tblAtblB ,但这就是问题的表达方式。

You can try this as well... 您也可以尝试...

select dt1,dt2,
       datediff(month,concat(left(dt1, 4),'-',right(dt1, 2),'-01'),concat(left(dt2, 4),'-',right(dt2, 2),'-01')) dateDiff 
from mytbl

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM