将date转换为int时出错

时间:2016-02-22 09:16:38

标签: sql-server

DECLARE @x nvarchar(max)
DECLARE @Employee bigint
DECLARE @StartDate date
DECLARE @EndDate date

SET @x = 'Select Distinct Att.Status
                ,ED.StartDate
                ,ED.EndDate
                ,u.FirstName
                ,u.Department
                ,ED.LeaveDays 
from EmployeeLeaveDetails ED
JOIN Employee e                 on ED.Employee = e.Employee 
                                and ED.IsDeleted = 0 
                                and e.IsDeleted = 0
JOIN Attendance a               on e.Employee = a.Employee
LEFT JOIN AttendanceStatus Att  on CAST(a.Status as nvarchar) = Att.Status  
                                and a.IsDeleted = 0 
                                and Att.IsDeleted = 0 
                                and Att.IsVacation = 1 
JOIN Users u                    on e.Users = u.Users 
                                and u.IsDeleted = 0
Where ED.Employee = ' +CAST(293 as nvarchar)+ ' 
                                and ED.StartDate = '+CAST('2016-01-01' as nvarchar)+' 
                                and ED.EndDate ='+CAST('2016-01-04' as nvarchar)+'
group by Att.Status 
        ,ED.StartDate
        ,ED.EndDate
        ,u.FirstName
        ,u.Department
        ,ED.LeaveDays'

1 个答案:

答案 0 :(得分:0)

我认为这些行是错误的来源:

and ED.StartDate = '+CAST('2016-01-01' as nvarchar)+' 
and ED.EndDate ='+CAST('2016-01-04' as nvarchar)+'

在最终的@x值中,它以sql的形式执行,它将变为

and ED.StartDate = 2016-01-01 
and ED.EndDate = 2016-01-04

2016-01-01看起来像是我们人类的日期,但SQL Server看到(计算的)整数:2014(2016减1减1)。 用这样的引号环绕日期(遗漏了CAST,因为我不明白你为什么要把日期字符串转换为nvarchar)。

and ED.StartDate = ''2016-01-01''' +' 
and ED.EndDate =''2016-01-04''' +'