Hi
I am getting error - Conversion failed when converting the varchar value 'SELECT MAX(docentry) FROM Department' to data type int.
SQL
ALTER PROCEDURE [dbo].[MaxDocEntry]
-- Add the parameters for the stored procedure here
@TableName VARCHAR(50)
,@DocEntry INT OUTPUT
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
SET @DocEntry = 'SELECT MAX(docentry) FROM ' + @TableName
ENDThanks

Naimish MakwanaRank #324 · 7.7K reputationPosted Sep 2, 2024, 2:13 AM EDT
To ensure that
@DocEntryis set to 1 if there are no records in the table, you can modify your stored procedure to handle this case. You can use theISNULLfunction to set a default value if theMAX(docentry)returnsNULL.Here’s the updated stored procedure:
ALTER PROCEDURE [dbo].[MaxDocEntry] @TableName VARCHAR(50), @DocEntry INT OUTPUT AS BEGIN SET NOCOUNT ON; DECLARE @SQL NVARCHAR(1000); DECLARE @Result INT; SET @SQL = 'SELECT @Result = ISNULL(MAX(docentry), 0) + 1 FROM ' + @TableName + ' WITH (TABLOCKX)'; EXEC sp_executesql @SQL, N'@Result INT OUTPUT', @Result OUTPUT; SET @DocEntry = @Result; ENDIn this version:
ISNULLfunction is used to return 0 ifMAX(docentry)isNULL.@DocEntryis set to 1 if there are no records.This way, if the table is empty,
@DocEntrywill be set to 1. If there are records, it will be set to the maximumdocentryvalue plus 1.Thanks
Naimish MakwanaRank #324 · 7.7K reputationPosted Sep 2, 2024, 1:18 AM EDT
The error you’re encountering is because you’re trying to assign a string to an integer variable. To fix this, you need to execute the dynamic SQL and then assign the result to the
@DocEntryvariable. Here’s how you can modify your stored procedure:ALTER PROCEDURE [dbo].[MaxDocEntry] @TableName VARCHAR(50), @DocEntry INT OUTPUT AS BEGIN SET NOCOUNT ON; DECLARE @SQL NVARCHAR(1000); DECLARE @Result INT; SET @SQL = 'SELECT @Result = MAX(docentry) FROM ' + @TableName; EXEC sp_executesql @SQL, N'@Result INT OUTPUT', @Result OUTPUT; SET @DocEntry = @Result; ENDIn this version:
@SQLvariable.sp_executesqlsystem stored procedure is used to execute the dynamic SQL and capture the result in the@Resultvariable.@DocEntryoutput parameter.This should resolve the conversion error you’re experiencing.
Thanks