nice one your code actually works but have to chance small changes in coding that time I got this error Conversion failed when converting the varchar value 'STR001' to data type int. Please help me
In this blog we will know how to autoincrement int datatype
as well as varchar datatype values in database using stored procedure while
inserting records into the tables.
Using int data type
Table Structure
Create table AutoIncrementId
(
id int,
name varchar(50)
)
Stored Procedure
ALTER procedure AutoIncrementIdpro
@name varchar(50)
as
declare @Id int
Select @Id=count(Id)+1 from AutoIncrementId
Begin
Insert into
AutoIncrementId values (@Id,@name)
End
Execution of Stored Procedure
EXEC dbo.AutoIncrementIdpro 'Raj'
EXEC dbo.AutoIncrementIdpro 'Ravi'
EXEC dbo.AutoIncrementIdpro 'Rahul'
Display result
SELECT *
FROM dbo.AutoIncrementId
Output
idname
1Raj
2Ravi
3Rahul
Using varchar datatype
CREATE TABLE Employee
(
ID VARCHAR(50)
, Name
VARCHAR(255)
)
Stored Procedure
ALTER PROCEDURE dbo.AutoIncrement_Id
(
@Name
VARCHAR(255)
)
AS
DECLARE @Max INT
, @ID
VARCHAR(10)
IF NOT EXISTS(SELECT ID FROM Employee)
BEGIN
SET @ID =
'E00001'
INSERT INTO
dbo.Employee(ID,Name)
VALUES(@ID,
@Name)
END
ELSE
BEGIN
SELECT @Max
= CONVERT(INT, SUBSTRING(CONVERT(VARCHAR(10),ID), 2, 10)) FROM Employee
shanifa SPosted Jun 21, 2018, 1:09 AM
SELECT @Max = CONVERT(INT, SUBSTRING(CONVERT(VARCHAR(10),ID), 2, 10)) FROM Employee can u explain this line
Meena SundharavradhanPosted May 3, 2016, 2:39 AM
nice one your code actually works but have to chance small changes in coding that time I got this error Conversion failed when converting the varchar value 'STR001' to data type int. Please help me