1 Create procedure [dbo].[InsertOriginalCreateName_Vendor] 2 @TableName nvarchar(50) 3 as 4 Begin 5 declare @UserApplicant nvarchar(50); 6 declare @CreatedDate datetime; 7 declare @OriginalDate datetime; 8 declare @code nvarchar(50); 9 declare @action nvarchar(50); 10 declare @id nvarchar(50); 11 declare @sql nvarchar(max) 12 set xact_abort on 13 begin tran 14 set @sql='declare _cur cursor for select id,[External Partner Number] from '+@TableName 15 exec (@sql) 16 open _cur 17 fetch next from _cur into @id,@code 18 print @id 19 while (@@fetch_status=0) 20 begin 21 begin try 22 if exists(select * from vendorheaders where code=@code) 23 begin 24 if exists(select * from vendoritems where vendorheaderid in(select id from vendorheaders where code=@code) and RoleActionId=2) 25 begin 26 select top 1 @CreatedDate=CreatedDate,@UserApplicant=UserApplicant,@action=RoleActionId from vendoritems where vendorheaderid in(select id from vendorheaders where code=@code) and RoleActionId=2 order by CreatedDate asc 27 28 set @sql='update '+@TableName+' set [date]='+''''+convert(VARCHAR(20),@CreatedDate,120)+''''+',[Project manager]='+''''+@UserApplicant+''''+' where id='+@id 29 exec (@sql) 30 end 31 else if exists(select * from vendoritems where vendorheaderid in(select id from vendorheaders where code=@code) and RoleActionId=4) 32 begin 33 select top 1 @CreatedDate=CreatedDate,@UserApplicant=UserApplicant,@action=RoleActionId from vendoritems where vendorheaderid in(select id from vendorheaders where code=@code) and RoleActionId=4 order by CreatedDate asc 34 35 set @sql='update '+@TableName+' set [date]='+''''+convert(VARCHAR(20),@CreatedDate,120)+''''+',[Project manager]='+''''+@UserApplicant+''''+' where id='+@id 36 exec (@sql) 37 end 38 39 else 40 begin 41 select top 1 @OriginalDate=CreatedDate from vendorheaders where code=@code order by CreatedDate asc 42 set @sql='update '+@TableName+' set [date]='+''''+convert(VARCHAR(20),@OriginalDate,120)+''''+' where id ='+@id 43 exec (@sql) 44 end 45 end 46 else 47 begin 48 set @sql='update '+@TableName+' set [Project manager]=''Not find this data'' where id='+@id 49 exec(@sql) 50 end 51 end try 52 53 begin catch 54 print ERROR_MESSAGE() 55 rollback tran 56 close _cur 57 deallocate _cur 58 return 59 end catch 60 61 fetch next from _cur into @id,@code 62 print @id 63 end 64 commit tran 65 close _cur 66 deallocate _cur 67 End