sql server - Assign non identity sequence to field based on another column on multiple row insert -
i have sql table in sql server 2008 purpose includes patient_id (primary), custno (char), recip_id (int)
1 - c01731 - 1 2 - c01731 - 2 3 - c01731 - 3 4 - c01732 - 1 5 - c01732 - 2 6 - c01732 - 3 7 - c01732 - 4 8 - c01733 - 1 9 - c01733 - 2
so when need insert single record use stored procedure...
create procedure [dbo].[jr_sp_nw_insertrecord] ( @custno varchar(max), @modwho varchar(max) ) begin set nocount on; --declare @retval int declare @rownum int set @rownum = (select max(recip_id)+1 usersmailingdata custno = @custno) insert dbo.usersmailingdata(custno,recip_id,modify, modifywho) values(@custno, @rownum, getdate(), @modwho) select cast(scope_identity() int) end
my problem need stored procedure @ highest number in column recip_id based on @custno , on insert of multiple rows increment number 1 each row inserted. recip_id can have gaps when records deleted not issue.
i assume problem you're inserting rows select statement, in case can use row_number() assign number rows, this:
insert dbo.usersmailingdata(custno,recip_id,...) select @custno, row_number() on (order colname) + @rownum ... tablename
the colname column in order want numbers calculated new rows.
your @rownum fetch has bug, doesn't work when there no rows customer.
Comments
Post a Comment