I'm trying to create a stored procedure for the query in
http://sqlfiddle.com/#!3/9aaa3/1 The parameters are EmpId and EmpName. The query works fine when all parameters are null and also when EmpId is not null.
The problem is, when sending the EmpName. I get no results when I say
EXEC GetEmployeeLeaves null, 's'
ALTER PROCEDURE GetEmployeeLeaves
(
@EmpId uniqueidentifier = null,
@EmpName nvarchar(50) = null
)
AS
BEGIN
IF @EmpId ='+'00000000-0000-0000-0000-000000000000'+'
SET @EmpId = NULL
IF @EmpName = ''
SET @EmpName = NULL
DECLARE @cols AS NVARCHAR(MAX), @query AS NVARCHAR(MAX)
SELECT @cols = STUFF((SELECT DISTINCT ',' + QUOTENAME(LeaveName)
from tblLeaveType
FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'),1,1,'')
SET @query = 'SELECT EmpId, EmpName,' + @cols + '
FROM
(
SELECT E.EmpId, E.EmpName, T.LeaveName, L.Days
FROM tblEmp E
LEFT OUTER JOIN tblEmpLeaves L ON E.EmpId = L.EmpId
LEFT OUTER JOIN tblLeaveType T ON L.TypeId = T.TypeId
WHERE
(E.EmpId = @EmpId OR @EmpId IS NULL)AND
(E.EmpName LIKE ''%@EmpName%'' OR @EmpName IS NULL)
) x
PIVOT
(
MAX(Days) FOR LeaveName IN (' + @cols + ')
) p
ORDER BY EmpId'
SET @paramDefinition = '@EmpId uniqueidentifier = null,
@EmpName nvarchar(50) = null'
execute sp_executesql @query, @paramDefinition ,@EmpId ,@EmpName
END