传入参数的动态枢轴

dynamic pivot with parameter passed in

我创建了这个在硬编码时可以工作的存储过程 (在 @WeekStart 和 @WeekEnd 的 where 子句中),

如果我尝试向查询@WeekStart 和@WeekEnd 添加参数,我会收到以下错误:

Must declare the scalar variable "@WeekStart".

我的目标是做这样的事情而不是硬编码:

exec dbo.GetTotals @WeekStart='2022-04-11',@WeekEnd='2022-04-25'

存储过程:

  CREATE PROCEDURE [dbo].[GetTotals]
@WeekStart Date,
@WeekEnd Date

    AS
begin
    set nocount on;
    --get row names
DECLARE 
    @columns NVARCHAR(MAX) = '', 
    @sql     NVARCHAR(MAX) = '';

-- select the category names
SELECT 
    @columns+=QUOTENAME(DepartmentName) + ','
FROM 
    DepartmentTable
ORDER BY 
    DepartmentName;

--set@colums variable
SET @columns = LEFT(@columns, LEN(@columns) - 1);

-- construct dynamic SQL
SET @sql ='
SELECT * FROM   
(
   select
    JobCode,
    DepartmentName,
    (COALESCE(MonTime, 0)+COALESCE(TueTime, 0)+COALESCE(WenTime, 0)+COALESCE(ThurTime, 0)+COALESCE(FriTime, 0)
                +COALESCE(SatTime, 0)+COALESCE(SunTime, 0)) as total
        
     
        
from TimeSheetTable

INNER JOIN DepartmentTable ON TimeSheetTable.DeptId=DepartmentTable.Id
inner join  JobCodeTable on TimeSheetTable.JobId=JobCodeTable.Id

--这有效-- -- WeekStartDate 在 ''2022-04-11'' 和 ''2022-04-11'' 之间的位置 -- --这是抛出一个错误-- @WeekStart 和@WeekEnd 之间的 WeekStartDate

) t 
PIVOT(
   sum(total)
   
    FOR DepartmentName IN ('+ @columns +')
    
)pivot_table
ORDER BY JobCode
'
---- execute the dynamic SQL
EXECUTE sp_executesql  @sql;

end
exec sp_executesql @Sql, N' @WeekStart Date, @WeekEnd Date', @WeekStart = @WeekStart, @WeekEnd = @WeekEnd