Please start any new threads on our new
site at https://forums.sqlteam.com. We've got lots of great SQL Server
experts to answer whatever question you can come up with.
Author |
Topic |
mtlmonk
Starting Member
6 Posts |
Posted - 2008-03-31 : 15:21:45
|
Hi,I have a stored procedure that does insert in a table with a column that is from a generated value (last no found in a text column for that same table) and some other stuff afterwards.It seems that if two calls to the stored procedures is happening at the same time, the generated value is the same for both since the 1st call did not finish inserting the record yet. Which is wrong obviously.Ex.:tblreceiptreceiptid, pk (identity column)receiptno, varchar(10)branchid, intCalls: exec OrderInsert @branchid = 7, @custid = 1exec OrderInsert @orderdate = 7, @custid = 1 (almost same time)Code of Stored Procedure:CREATE PROCEDURE ReceiptHeaderInsert@branchid INT,@custid INT,@receiptno VARCHAR(10) = NULLASBEGINDECLARE @receiptid INTDECLARE @cnt INTSET NOCOUNT ONINSERT INTO tblReceipt (receiptno)VALUES (dbo.uf_GenReceiptNo(@branchid))IF @@ERROR <> 0BEGIN SELECT 0 RETURNENDSET @receiptid = @@IDENTITYIF @RECEIPTNO IS NULL BEGIN SELECT @receiptno = receiptno FROM TBLRECEIPT WHERE RECEIPTID =@receiptidEND[...] some other stuff........SELECT @receiptid 'RECEIPTID', @receiptno 'RECEIPTNO', @modidate 'modidate'ENDGOCode of UDF used in Stored procedure to generate receiptnoCREATE FUNCTION uf_GenReceiptNo(@branchid INT) RETURNS VARCHAR(30)ASBEGINDECLARE @branchcode VARCHAR(10)DECLARE @count INTDECLARE @rv VARCHAR(30)SET @branchcode = (SELECT branchcode FROM tblBranch WHERE branchid = @branchid)--Gets the last receiptno foundSET @count = (SELECT MAX(CONVERT(INT, SUBSTRING(receiptno, CHARINDEX('-', receiptno) + 1, DATALENGTH(receiptno)))) FROM tblReceipt WHERE receiptid IN (SELECT receiptid FROM tblBranchReceipt WHERE branchid = @branchid)) IF @count IS NULL SET @count = 0--Increments by oneSET @count = @count + 1SET @rv = @branchcode + '-' + CONVERT(varchar(9), @count)RETURN @rvEND |
|
spirit1
Cybernetic Yak Master
11752 Posts |
|
LoztInSpace
Aged Yak Warrior
940 Posts |
Posted - 2008-04-02 : 02:38:43
|
This will seriously limit your concurrency though. Best not to do what you are doing at all and use the identity column as your receipt number.I can tell this will degenerate into a 'but I need it to be gap free' discussion. |
 |
|
|
|
|
|
|