简体   繁体   English

存储过程未返回所需结果

[英]Stored Procedure Doesn't return required result

I have a table EmployeeAttendance and Users and when i try to get the records using the below query and passing null value to the @userName parameter it doesn't return any records...there might be some problem in the query... 我有一个表EmployeeAttendance和Users,当我尝试使用以下查询获取记录并将空值传递给@userName参数时,它不返回任何记录...查询中可能存在一些问题...

Can any one help me on this 谁可以帮我这个事

 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

And when i pass the @userName with some particular string then it returns correct results but if i pass the null value to the @userName then it return the nothing. 当我通过带有特定字符串的@userName传递时,它将返回正确的结果,但是如果我将null值传递给@userName,则它将不返回任何内容。

So i want, when i pass null value to @userName it return all the results. 所以我想,当我将空值传递给@userName时,它返回所有结果。

Oh yes. 哦是的 There is a problem. 有一个问题。 If you ad null to a string the whole string will be null. 如果将null设置为字符串,则整个字符串将为null。 'abc'+null = null 'abc'+ null =空

Dont declare it to null 不要将其声明为null

@userName nvarchar(100) = '';

And change 并改变

(u.UserName like ''%'+@userName+  '%'' OR '''+@userName+''' ='''' )

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

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