“从字符串转换日期和/或时间时转换失败。”错误

时间:2018-09-11 08:26:11

标签: sql-server

我有以下查询:

DECLARE @Month int
DECLARE @Year int

set @Month = 2 
set @Year = 2004  

Declare @MonthStartDate datetime
declare @MonthEndDate datetime  

set @MonthStartDate = 'select DATEADD(month,@Month-1,DATEADD(year,@Year-1900,0))' 

set @MonthEndDate = 'select DATEADD(day,-1,DATEADD(month,@Month,DATEADD(year,@Year-1900,0)))'

返回@MonthStartDate,@MonthEndDate

但是它返回:

  

“从字符串转换日期和/或时间时转换失败。”

这是怎么了?

3 个答案:

答案 0 :(得分:1)

您应该使用DateTime表达式而不是字符串文字。只需删除引号即可:

DECLARE @Month int

DECLARE @Year int

set @Month = 2 

set @Year = 2004  

Declare @MonthStartDate datetime
declare @MonthEndDate datetime  

set @MonthStartDate = DATEADD(month,@Month-1,DATEADD(year,@Year-1900,0))

set @MonthEndDate = DATEADD(day,-1,DATEADD(month,@Month,DATEADD(year,@Year-1900,0)))

答案 1 :(得分:1)

或者,您也可以按照以下方式使用。

select @MonthStartDate = DATEADD(month,@Month-1,DATEADD(year,@Year-1900,0))
select @MonthEndDate = DATEADD(day,-1,DATEADD(month,@Month,DATEADD(year,@Year-1900,0)))

答案 2 :(得分:0)

查看您的查询(因为您对问题的描述不够多)据我了解,您正在尝试获取给定月份的第一天和最后一天。如果您使用的是SQL Server 2012版或更高版本,则有一个名为EOMONTH()的内置函数,可用于计算任何给定月份的结束日期。否则,您可以在SQL Server的任何版本上尝试以下方法

Declare @MonthStartDate datetime,
        @MonthEndDate datetime,
        @Year int,
        @Month int --It's Better to Declare all the variables in the same space for easy handling

SELECT
    @Month = 2,
    @Year = 2004  -- Common Assignments can be done together

;WITH MNT
AS
(
    SELECT
        MonthStartDate = CAST(@Month AS VARCHAR(20))+'/01/'+CAST(@Year AS VARCHAR(20)) -- Hardcoded Day as 1 since Month Start always at 1
)
SELECT
    @MonthStartDate = MonthStartDate,
    @MonthEndDate = DATEADD(DAY,-1,DATEADD(MONTH,1,MonthStartDate))
    FROM MNT