Hello All,
I have to insert the rows from the #table to the user table. I have written a cursor to implement this process.
The #table has two rows which shoule be inserted in the user table. While inserting records, I have to insert the PK column as well. So I get the max(col) from the table and add one number.
I have to commit first insert since I have to use max(col) and aviod duplicate PK reference. But the cursor goes in the infinite loop.
Can anyone tell me what am I missing here?
Here is the code
Thanks in advance.
techiPA
I have to insert the rows from the #table to the user table. I have written a cursor to implement this process.
The #table has two rows which shoule be inserted in the user table. While inserting records, I have to insert the PK column as well. So I get the max(col) from the table and add one number.
I have to commit first insert since I have to use max(col) and aviod duplicate PK reference. But the cursor goes in the infinite loop.
Can anyone tell me what am I missing here?
Here is the code
Code:
DECLARE @SaveError int,
@Name varchar(50),
@Code varchar(50),
@Category varchar(50),
@RefID int
SET NOCOUNT ON
CREATE TABLE #AddNew
(
Code varchar(50),
Revised varchar(50),
Name varchar(50),
Category varchar(50)
)
INSERT INTO #AddNew (Code, Revised, Name, Category)
SELECT 'code1','Newcode1','Name1', 'Cate1'
INSERT INTO #AddNew (Code, Revised, Name, Category)
SELECT 'code2','Newcode2','Name2', 'Cate2'
IF @@ROWCOUNT > 0
BEGIN
DECLARE @NewCur CURSOR
SET @NewCur = CURSOR FOR
SELECT Code, Name, Category
FROM #AddNew
OPEN @NewCur
FETCH NEXT FROM @NewCur INTO @Code, @Name, @Category
WHILE @@Fetch_Status = 0
BEGIN TRAN
INSERT INTO dbo.Table1
(ColID, SID, Name, ExtRef, Category, Active)
SELECT (SELECT max(ColID)+1 FROM dbo.Table1), 0, @Name, @Code, @Category, 1
FROM #AddNew
IF @@ERROR <> 0
BEGIN
ROLLBACK TRAN
RAISERROR('Error encountered', 15, 1)
RETURN
END
ELSE
COMMIT TRAN
FETCH NEXT FROM @NewCur INTO @Code, @Name, @Category
END
CLOSE @NewCur
DEALLOCATE @NewCur
END
Thanks in advance.
techiPA