繁体   English   中英

在 SQL 中的 Report Builder 查询中将字符串转换为日期/时间

[英]Convert String to Date/Time in Report Builder query in SQL

我有一列 ENTRY_MONTH,其中包含日期作为字符串,例如 11/2017。

我正在尝试将该列转换为日期时间,最好是每个月的最后一天,因此在上面的示例中为 11-30-2017。

我试过了

CONVERT(datetime, ENTRY_MONTH, 110)

无济于事。 有什么建议吗?

select convert(datetime,right(entrymonth,4) + left(entrymonth,2) + '01')

有很多方法可以做到这一点。

Declare @strDate varchar(10) = '11/2017'

-- concatenate '01/' to get the first date of the month.
--  (it is needed to make a proper date, 
-- and not necessary to make it the first date, it can be '17/' as well 
Select '01/' + @strDate
Select Convert(DateTime,'01/' + @strDate, 103)
-- the EOMONTH can be used here
Select EOMONTH(Convert(DateTime,'01/' + @strDate, 103))

在你的情况下:

 EOMONTH(Convert(DateTime,'01/' + ENTRY_MONTH, 103) 

您可以尝试以下方法:

DECLARE @MyDate varchar(16) = '11/2017'
SELECT DATEADD(d,-1,DATEADD(m,1,CONVERT(datetime, '1/' + @MyDate, 103)))

这使用欧洲格式,其中一天是第一位的。 添加一个月,然后请一天假,带您到月底。

如果你 go 一步一步转换和格式化,你可以这样做(结果中也显示了中间结果):

DECLARE @entryMonth VARCHAR(7) = '11/2017';

SELECT
    @entryMonth AS "entry month",
    FORMAT( -- create a date from the parts you have in the varchar and a 1 for the day
        DATEFROMPARTS(RIGHT(@entryMonth, 4), LEFT(@entryMonth, 2), 1),
        'MM-dd-yyyy'    -- and format it the way you want
    ) AS "First of month",
    FORMAT(
        DATEADD(MONTH,
                1,  -- add a month in order to get the first of next month
                FORMAT(
                    DATEFROMPARTS(RIGHT(@entryMonth, 4), LEFT(@entryMonth, 2), 1),
                    'MM-dd-yyyy')
        ),
        'MM-dd-yyyy'
    ) AS "First day next month",
    FORMAT(
        DATEADD(DAY,
                -1, -- subtract a day from the first of next month
                DATEADD(MONTH, 1, FORMAT(
                                    DATEFROMPARTS(RIGHT(@entryMonth, 4), LEFT(@entryMonth, 2), 1),
                                    'MM-dd-yyyy'))
                ),
        'MM-dd-yyyy'
    ) AS "Last day entry month"
entry month     First of month  First day next month    Last day entry month
    11/2017         11-01-2017            12-01-2017              11-30-2017

暂无
暂无

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

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