Monday, March 26, 2012

MS SQL Server Locking problem!

Hi,
MS SQL server has many sort of locking levels and locking modes.
Among all of these can I know what best suit for me when simulating the identity column property to avoid dublicating rows with same number, such as :
-------------------
CREATE PROC NewNumber
@.OwnerNo int,
@.ReturnValue int OUTPUT
AS

DECLARE @.NewNum int
DECLARE ctr_cursor CURSOR FOR
SELECT MAX(MessageNo) AS MaxNumber FROM tblMessages WHERE OwnerNo = @.OwnerNo

OPEN ctr_cursor
FETCH NEXT FROM ctr_cursor INTO @.NewNum
If @.@.FETCH_STATUS = 0
BEGIN
SELECT @.NewNum = @.NewNum + 1
END
ELSE
BEGIN
SELECT @.NewNum = 1
END

SELECT @.ReturnValue = @.NewNum

CLOSE ctr_cursor
DEALLOCATE ctr_Cursor

GO
-------------------
I can't use the identity (seed & increment) property with my case because my column is not unique, the uniqueness is built on two columns.

I would really appreciate your help :confused: .
Thankstoo bad!
I can't find some one help me:(
still waiting:confused:|||Create a table named UniqueID with 2 columns
TableName Varchar(15)
LastID Int

Add a record with the table or value name and the number you want to start with.

Create a stored procedure to increase the number and call it when you need to add a record to your other table.

This will work faster than searching the table every time.

CREATE procedure GetNextTableUID (@.tableName varchar(20)) as

/* Gets the next UniqueID for the given table.
* If there is no entry for that table, adds one.
*/

begin transaction;

declare @.thisUID int;

set @.tableName = lower(@.tableName);

-- Get next UID

select @.thisUID = LastUID + 1
from UniqueID UPDLOCK HOLDLOCK
where lower(TableName) = lower(@.tableName);

-- Update UniqueID table

if ((@.@.rowcount = 0) or (@.thisUID is null)) begin
set @.thisUID = 1;
insert UniqueID values (@.tableName, @.thisUID);
end else
update UniqueID set LastUID = @.thisUID
where lower(TableName) = lower(@.tableName);

-- Check for errors

if @.@.error <> 0 begin
rollback transaction;
raiserror( 'SQL Error: GetNextTableUID', 16, -1 )
return 0;
end

commit transaction;
return @.thisUID;

GO|||I thanked god, that you were there!:rolleyes:

I recieved two more professional solutions by email, but yours was the best, you got me stright to the point.

Many many thanks
All the best:D

No comments:

Post a Comment