我正在尝试根据当前日期获得正确的年份并附加到会计年度月份日期部分,但我收到的错误是它不是整数。想法或想法?
`ALTER FUNCTION [dbo].[fn_CS_IssuedMODs] (@currentDate DATE)
RETURNS TABLE
AS
RETURN
(SELECT cs.Specialist, CASE WHEN COUNT(mn.mod_number_id) IS NULL
THEN 0 ELSE COUNT(mn.mod_number_id) END AS IssuedMODS,
cs.user_certificateSerialNumber
FROM dbo.tbl_modificationNumbers AS mn RIGHT OUTER JOIN
dbo.vw_ContractSpecialists AS cs ON mn.mod_specialist_id = cs.user_certificateSerialNumber
WHERE (mn.statusID = 10) AND effective_date between '10/1/'+DATEPART(YEAR,@currentDate)
+ CASE WHEN DATEPART(MONTH, @CurrentDate) >= 10 THEN -1 ELSE 0 END AND '09/30/'+DATEPART (YEAR,@currentDate)
GROUP BY cs.Specialist, cs.user_certificateSerialNumber`
答案 0 :(得分:1)
让我们为测试创建一些变量:
DECLARE @currentDate DATETIME = '4/2/2014'
DECLARE @FiscalYearStart DATETIME
DECLARE @FiscalYearEnd DATETIME
现在我们要检查当前日期是在10月1日之前还是之后,如果是,我们将使用前一年开始会计年度,否则我们将在新的会计年度。
SELECT @FiscalYearStart =
(
CASE
WHEN DATEPART(MONTH, @currentDate) < 10 THEN
DATEADD(MONTH,9, DATEADD(YEAR, DATEDIFF(YEAR, 0, @currentDate) - 1, 0))
ELSE
DATEADD(MONTH,9, DATEADD(YEAR, DATEDIFF(YEAR, 0, @currentDate), 0))
END
),
@FiscalYearEnd =
(
CASE
WHEN DATEPART(MONTH, @currentDate) < 10 THEN
DATEADD(MONTH,9, DATEADD(YEAR, DATEDIFF(YEAR, 0, @currentDate), 0))
ELSE
DATEADD(MONTH,9, DATEADD(YEAR, DATEDIFF(YEAR, 0, @currentDate) + 1, 0))
END
)
SELECT @FiscalYearStart As FiscalYearStart, @FiscalYearEnd As FiscalYearEnd
输出:
FiscalYearStart FiscalYearEnd
2013-10-01 00:00:00.000 2014-10-01 00:00:00.000
现在,您可以在查询中使用effective_date >= @FiscalYearStart AND effective_date < @FiscalYearEnd
来提取当年的正确数据。
答案 1 :(得分:0)
而不是datepart()
使用datename()
。或者,对字符串进行明确的cast()
。
+
运算符在SQL Server中重载。当遇到一个数字时,它被视为加法 - 你不能添加字符串。
我无法弄清楚你的代码应该做什么。可能有更好的方法来实现你想要的。对于初学者,您应该使用ISO标准日期格式(YYYYMMDD或YYYY-MM-DD)作为常量。
答案 2 :(得分:0)
试试这个:
ALTER FUNCTION [dbo].[fn_CS_IssuedMODs] (@currentDate DATE)
RETURNS TABLE
AS
RETURN
(SELECT cs.Specialist, CASE WHEN COUNT(mn.mod_number_id) IS NULL
THEN 0 ELSE COUNT(mn.mod_number_id) END AS IssuedMODS,
cs.user_certificateSerialNumber
FROM dbo.tbl_modificationNumbers AS mn RIGHT OUTER JOIN
dbo.vw_ContractSpecialists AS cs ON mn.mod_specialist_id = cs.user_certificateSerialNumber
WHERE (mn.statusID = 10) AND effective_date between Cast(DATEPART(YEAR, DateAdd(Year, CASE WHEN DATEPART(MONTH, @CurrentDate) >= 10 THEN -1 ELSE 0 END, @currentDate)) as varchar) + '-10-1'
AND Cast(DATEPART(YEAR,@currentDate) as varchar) + '-09-30'
GROUP BY cs.Specialist, cs.user_certificateSerialNumber