0

我正在尝试为http://sqlfiddle.com/#!3/9aaa3/1中的查询创建一个存储过程 。参数是 EmpId 和 EmpName。查询工作正常。当参数在“@query”部分中声明时,“执行存储过程”不会提示输入参数。当在“@query”之外声明时,我可以选择发送参数,但无论过滤器如何,它总是返回所有行。

所以.....这是正确的方法:

CREATE PROCEDURE GetEmployeeLeaves
BEGIN
 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 = '
                 DECLARE @EmpId uniqueidentifier = null,   
                         @EmpName nvarchar(50) = null
                 IF @EmpId ='+'00000000-0000-0000-0000-000000000000'+'
                 SET @EmpId = NULL
                 IF @EmpName = '+''+'
                 SET @EmpName = NULL
                 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.EmpNameLIKE %@EmpName% OR @EmpName IS NULL)                
                 ) x
                PIVOT
                 (
                  MAX(Days) FOR LeaveName IN (' + @cols + ')                      
                 ) p 
               ORDER BY EmpId'
               execute  sp_executesql @query;
END
4

1 回答 1

0

这些链接帮助我解决了这个问题

http://www.codeproject.com/Articles/20815/Building-Dynamic-SQL-In-a-Stored-Procedure

如何在存储过程的 t-sql 动态语句中使用 LIKE?

于 2013-11-12T15:33:57.460 回答