sql server—使用动态sql将参数传递到数据透视表数据中的存储过程

hfyxw5xn  于 2021-07-26  发布在  Java
关注(0)|答案(0)|浏览(182)

我试图将一个参数传递到存储过程中,以筛选select语句中的数据,但使用该参数时,它会给出错误消息:列名“sessionid2075”无效。当我在where子句中使用静态值时,这个过程运行良好。你能帮我解决这个问题吗。我检查了所有以前的答案,找不到有效的解决办法。

Alter PROCEDURE [dbo].GetPivotFeeReport
(
@SessionId varchar(50) 
)
as
begin 

DECLARE @SQL as VARCHAR(MAX)
DECLARE @Columns as VARCHAR(MAX)

SET NOCOUNT ON;

SELECT @Columns =
COALESCE(@Columns + ', ','') + QUOTENAME(GroupHeaderValue)
FROM
   (SELECT DISTINCT mgh.GroupHeaderValue
    FROM   StudentFeeDetail sf
           INNER JOIN MasterGroupHeaderValue mgh
           ON mgh.GroupHeaderValueId = sf.FeeForId

   ) AS B
ORDER BY B.GroupHeaderValue

SET @SQL = 'SELECT ClassName,' + @Columns + ',TOTAL
FROM
(
 SELECT 
                distinct mc.className,
                sf.FinalAmount,
                mgh.GroupHeaderValue,
                Sum (isnull(sf.FinalAmount,0)) over (partition by ClassName)  AS TOTAL
                --0 AS TOTAL
         FROM   StudentFeeDetail sf 
                INNER JOIN StudentAdmission sa 
                  ON sa.AdmissionId = sf.AdmissionId
                INNER JOIN MasterClass mc
                  ON mc.ClassId = sa.ClassId
                INNER JOIN MasterGroupHeaderValue mgh
                  ON mgh.GroupHeaderValueId = sf.FeeForId
        WHERE   sa.SessionId = (' + @SessionId + ')  -- this is where I am trying to use the parameter when used static value like this ''SessionId2075'' the procedure works fine
        and sf.FeeAmt >0
        GROUP BY className, FinalAmount, GroupHeaderValue

) as PivotData
PIVOT
(
   sum(FinalAmount)
   FOR GroupHeaderValue IN (' + @Columns + ')  
) AS PivotResult

ORDER BY (ClassName) 
'

EXEC ( @sql)

end

暂无答案!

目前还没有任何答案,快来回答吧!

相关问题