I'm copying data from one table to another and during the copy i'm adding a autogenerated number.
The below query is a job that runs every day to add invoices for a specific day into the table.
insert into dbo.tblabc (InvoiceNumber, AgentId)
select [dbo].[udf_GetInvoiceNumber](AgentId),AgentId from dbo.tblxyz
The function [dbo].[udf_GetInvoiceNumber](cd.AgentId) returns the InvoiceNumber based on the Agent already available.
//Function
ALTER function [dbo].[udf_GetInvoiceNumber](@AgentId int)
returns varchar(50)
begin
DECLARE @JC varchar(50) = 0
if exists(SELECT count(agentid) from dbo.tblabc where AgentId = @AgentId and year(CreatedDate) = year(getdate()) group by agentid)
begin
Set @JC = (SELECT count(agentid) from dbo.tblabc where AgentId = @AgentId and year(CreatedDate) = year(getdate()) group by agentid)
end
Set @JC = (Select concat('ALD/SHJ/',year(getdate()),'/INV/000', @JC + 1))
return @JC
end
Now, this doesn't work and updates only one row with InvoiceNumber when multiple rows are added at the same time.
Any other way to achieve this?