我有一个表EmployeeAttendance和Users,当我尝试使用以下查询获取记录并将空值传递给@userName参数时,它不会返回任何记录...查询中可能存在一些问题。 ..
任何人都可以帮助我吗
declare @month int =12,
@year int=1,
@orgID int=1,
@userName nvarchar(100) = null;
DECLARE @lastDay int;
-- calculations
DECLARE @startDate datetime, @endDate datetime
SET @startDate = convert(varchar, @year) + '-' + convert(varchar, @month) + '-1'
set @endDate = DATEADD(s,-1,DATEADD(mm, DATEDIFF(m,0,@startDate)+1,0))
set @lastDay = day(@endDate) --last day of month
declare @day int
set @day = 2
declare @days varchar(max)
set @days = '[1]'
WHILE (@day <= @lastDay)
BEGIN
set @days = @days + ',[' + convert(varchar, @day) + ']'
set @day = @day + 1
END
declare @query varchar(max)
set @query = '
SELECT USerID,Name,' + @days +
'
FROM
(
SELECT u.ID as UserID, u.FirstName + '' ''' + ' ' + ' + u.LastName as Name, InTime,Outtime,isPresent, day(Date) as day FROM users u
LEFT join EmployeeAttendance e on e.USerID = u.ID AND [Date] between '''+ cast( @startDate as varchar)+' '' and '''+ cast( @endDate as varchar)+' ''
left join Employee emp on emp.UserID= u.ID
where emp.OrganisationID =' +cast( @orgID as varchar)+'
and(u.UserName like ''%'+@userName+ '%'' OR '''+@userName+''' IS NULL)
) AS SourceTable
PIVOT
(
MAX(InTime)
FOR day IN ( ' + @days + ')' + '
) AS PivotTable
;'
print @query;
exec(@query);
GO
当我使用某个特定字符串传递@userName时,它会返回正确的结果,但如果我将空值传递给@userName,则它将返回任何内容。
所以我想,当我将null值传递给@userName时,它会返回所有结果。
答案 0 :(得分:1)
哦,是的。这儿存在一个问题。如果您对字符串返回null,则整个字符串将为null。 'abc'+ null = null
不要将其声明为null
@userName nvarchar(100) = '';
并改变
(u.UserName like ''%'+@userName+ '%'' OR '''+@userName+''' ='''' )