Below is my stored procedure. I want use stored procedure select all row of date from tbl_member and insert 2 table. But it’s not work. Some one can help me?
Create PROCEDURE sp_test AS BEGIN SET NOCOUNT ON; Declare @A Varchar(255), @B Varchar(255), @C Varchar(255), @D int Declare Table_Cursor Cursor For select A, B, C from tbl_Member Open Table_Cursor Fetch Next From Table_Cursor Into @A, @B, @C While(@@Fetch_Status=0) Begin Exec( 'insert into NewMember (A, B, C, D) values (@A, @B, @C, @D) set @D = @@IDENTITY Insert into MemberId (Mid) VALUES(@D) ) Fetch Next From Table_Cursor Into @A, @B, @C End Close Table_Cursor Deallocate Table_Cursor END GO
The first thing I can see here is that you are using a cursor when you don’t need to. You can rewrite the first query as:
Then, I would have an INSERT trigger against NewMember that inserted the identity column.
BTW – it’s a bad idea to use @@IDENTITY to get the identity of an insert. Use the SCOPE_IDENTITY function instead.