Hi
I am getting error - Must declare the table variable "@TableName"
CREATE PROCEDURE MaxDocEntry
-- Add the parameters for the stored procedure here
@TableName VARCHAR(50) = NULL
,@DocEntry INT OUTPUT
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
SELECT
@DocEntry = MAX(docentry)
FROM
@TableName
END
GO
Prasad RaveendranPosted Sep 2, 2024, 3:35 AM
The error occurs because SQL Server does not support dynamic table names using variables directly in SQL queries. You cannot use
@TableNameas a table reference in aSELECTstatement this way. To achieve this, you need to construct a dynamic SQL query usingsp_executesql.Here's how you can modify your procedure:
Explanation:QUOTENAME(@TableName)ensures that the table name is properly escaped to avoid SQL injection issues.sp_executesqlprocedure allows for the execution of dynamic SQL with parameterized queries. We pass@DocEntryas an output parameter to capture the result of theMAX(docentry)query.This should resolve the error and allow you to dynamically query the table specified by
@TableName.