Hi
I am getting error - Conversion failed when converting the varchar value 'SELECT MAX(docentry) FROM Department' to data type int.
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
END
Thanks
Naimish MakwanaPosted Sep 2, 2024, 6:13 AM
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:
In 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 MakwanaPosted Sep 2, 2024, 5:18 AM
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:In 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