Unable to resolve: 'Must declare the scalar variable "@Parameter"`'

2.5k views Asked by At

I need to enter a parameter in the pivot down below in the stored procedure. but it states, "Must declare the scalar variable "@pWeek"."

I have tried to declare it every which way, but I am unable to figure this out. Everything else is fine on this coding as I get the numbers I want, the way I want them. I just need to be able to put this in an SSRS and be able to enter a parameter. Thank you.

GO
/****** Object:  StoredProcedure [dbo].[QB_ACCOUNT_SUMMARY]    Script Date: 6/19/2015 12:42:12 PM ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER ON
GO

ALTER PROCEDURE [dbo].[QB_ACCOUNT_SUMMARY]

@pWeek int

as
SET NOCOUNT ON

declare @AccountRef_Fullname AS  NVARCHAR(MAX)



select  @AccountRef_Fullname = COALESCE(@AccountRef_Fullname + ',', '') + '['+ AccountRef_Fullname + ']'

from 
(
select distinct Accountref_fullname 
from (select accountref_fullname from journalcreditlinedetail)JournalCreditLine
union
(select accountref_fullname from journaldebitlinedetail)
union
(select accountref_fullname from txnexpenselinedetail)
union
(select accountref_fullname from depositlinedetail)
union
(select discountaccountref_fullname from [appliedtotxndetail])
) pAccountRef_Full_Name


declare  @Sql NVARCHAR(MAX)


set @Sql = N' SELECT [REAL WEEK], [LTWS WEEK], [REAL YEAR], [LTWS YEAR], [LTWS PERIODS], ' + @AccountRef_Fullname 

+ 'from 

(SELECT     * from Account_Summary_View
where Week = @pWeek
   )Account_Data '

+'  PIVOT ('
+ '  sum(amount)   for   AccountRef_FullName in ('+ @AccountRef_Fullname +')'
+'  )  AS PivotTable '


--+' )Data '
 exec (@Sql)

 ;
1

There are 1 answers

2
Tab Alleman On BEST ANSWER

Change this:

where Week = @pWeek

To this:

where Week = ''' + CAST(@pWeek AS varchar(31)) + '''

Explanation: You're using dynamic sql; putting together a string that contains a SQL command and then executing it. That dynamic string doesn't have access to parameters and variables that were declared outside of itself. So it doesn't recognize the @pWeek parameter. You didn't declare it IN the dynamic sql string.

When you do it the way I showed you, you are concatenating the VALUE of @pWeek into the string, so that, for instance if you passed a value of 1 to @pWeek, then the string that gets executed would contain where Week = '1', which SQL has no trouble understanding.

You were already doing exactly this with this line in your existing code:

 AccountRef_FullName in ('+ @AccountRef_Fullname +')'