Question : SQL Server Stored Procedure - Must declare the scalar variable

I have written a stored procedure inside of SQL Server 2008.  When I attempt to execute the stored procedure, I get the following error:

Msg 137, Level 15, State 2, Line 1
Must declare the scalar variable "@Year".

I've included the code for the stored procedure.
Code Snippet:
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
32:
33:
34:
35:
36:
37:
38:
USE [CW2010]
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

ALTER PROCEDURE [dbo].[spRob_Test]
@Sorter int ,
@Lane int , 
@ErrorCode int OUTPUT
AS

DECLARE @Now		DateTime
DECLARE @Year		Int
DECLARE @Month		Int
DECLARE @Day		Int
DECLARE @Hour		Int
DECLARE @Divert		Int

SET @Now = GetDate()
SET @Year = DatePart(year, @Now)
SET @Month = DatePart(month, @Now)
SET @Day = DatePart(day, @Now)
SET @Hour = DatePart(hour, @Now)

SET NOCOUNT ON

-- SELECT row(s) from the table
DECLARE @query varchar(2000)

SET @query = 'SELECT * FROM tblSorterCounts WHERE DatePart(Year, DateTimeStamp) = @Year AND DatePart(month, DateTimeStamp) = @Month AND DatePart(day, DateTimeStamp) = @Day AND Hour = @Hour AND Sorter = @Sorter AND Lane = @Lane'
EXEC(@query)

-- Get the Error Code for the statment just executed
SET @ErrorCode = @@ERROR

Answer : SQL Server Stored Procedure - Must declare the scalar variable

You have all the variables in the string so they are not passed. You would need to use execSQL and pass in the variables if entirely neccessary to have this as dynamic sql. If that is the entire procedure then I am not sure I need to see the need to do so.
See: http://www.dba-sql-server.com/sql_server_tips/t_super_sql_460_dynamic_sql.htm

Or use SET
or just run it as a query.

By preference you would just use

SELECT * FROM ....

without making a query string and executing it
1:
2:
3:
@query = 'SELECT * FROM tblSorterCounts WHERE DatePart(Year, DateTimeStamp) = '+ @year + '......

--'' escapes a single quote so the 
Random Solutions  
 
programming4us programming4us