Locking Records In Sql Server

Feb 28, 2006

Hi,

How can i handle record locking in sql server?

 

 

View 1 Replies


ADVERTISEMENT

Locking Records In SQL Server From VB.net

Jan 5, 2004

In the application I'm working on, I need to be able to use different locks on my records during certain transactions. I need to know how to do this programmatically from within VB.net. If someone can show me an example of how to do this or show me where I could find some, I'd appreciate that.

Thanks.

View 2 Replies View Related

Locking Records

Feb 1, 2000

Hi

I've got table JOBS with JOB_ID, ORIGINATOR_ID etc. I prepare stored procedure that creates job, that mean,
inserts new record in table JOBS, and return JOB_ID as a result.

return (select MAX (JOB_ID) from JOBS where ORIGINATOR__ID = PARTICULAR_USER_ID)

The problem is when user is logged in two stations, runs two application and create job at the same time.
It is possible that both application receive the same MAX (JOB_ID)

Any suggestions how to lock records, or do it in a different way.

Michal

View 2 Replies View Related

Need Help With Records Not Locking...

Oct 18, 2006

Hello,
Can anyone help find a solution to a strange record locking problem in SQL 2000?

This stored procedure is run every two seconds by two workstations to auto-process specialized "jobs". This convoluted code began as a simple update statement, but as grown to this in an effort to prevent the two workstations from picking up the same record at the same time. Unfortunately, the machines are STILL managing to pickup the same job, which seems to be indicating some form of record locking issue.

We've tried a number of locking hints, single BEGIN/COMMIT transaction command sets, and now a granular pair of transactions complete with additional filtering in the update command's where clause, but the two client machines continue to get the same job row.

Any thoughts on how to ensure that once once machine "grabs" a job, the other will not somehow get the same record ??

Here's the current state of the procedure code:

create    Procedure dbo.spGetWFAutoJob216
@strActionSelected as varchar(150)
--stractionselected have all the selected actionid, seperated by comma.

as
Declare @JobID as varchar(10)
Declare @FoundJobID as varchar(10)
Set @JobID = -100
Set @FoundJobID = -100

begin tran
Select top 1 @FoundJobID = JobID from WFJob J
Join WFAutoJobDetail AJD on (AJD.WFActionID = J.ActionID and CharIndex(cast(ajd.wfactionid AS VARCHAR), @strActionSelected) > 0)
where isnull(J.Status, 'P') = 'P'
Order By J.Priority Asc, J.enteredDate ASC
commit tran


Begin Tran
 
Update WFJob
Set Status = 'I',
    @JobID = jobID
where isnull(Status, 'P') <> 'I' and JobID = @FoundJobID

insert into wfjoblogger values (host_name(), getdate(), @FoundJobID, @JobID)

Commit Tran

Select Coalesce(A.Name, 'No Action Record') as ActionName, *
from WFJob J
Join WFAutoJobDetail AJD on AJD.WFActionID = J.ActionID
Left Join WFAction A On A.ID = J.ActionID
Where JobID = @JobID and isnull(J.Status, 'P') = 'I'
go

And here's an example of the log table results showing a few instances of the two machines getting the same jobid records:










LogID
Host
datetime
foundjob
thejob

51
SVR2
52:05.110
1049419
1049419

52
SVR2
52:12.140
1042784
1042784

53
SVR2
52:20.843
1052719
1052719

54
SVR2
53:12.920
1043496
1043496

55
SVR2
53:23.250
1045710
1045710

56
SVR2
53:30.297
1055096
1055096

57
SVR2
54:21.000
1043511
1043511

58
SVR2
55:06.907
1055095
1055095

59
SVR2
56:08.237
1055092
1055092

60
IS-1004
56:11.407
1055092
1055092

61
SVR2
56:43.313
1045366
1045366

62
SVR2
56:52.703
1052723
1052723

63
IS-1004
57:00.190
1052723
1052723

64
IS-1004
57:23.300
1055085
1055085

65
SVR2
57:25.970
1055085
1055085

66
IS-1004
58:24.877
1052286
1052286

67
IS-1004
58:44.877
1043491
1043491

68
IS-1004
59:08.270
1052727
1052727

69
SVR2
59:13.207
1052727
1052727

View 2 Replies View Related

Vb.net 2005, Sql2005 Not Locking The Records While Editing

Dec 18, 2007

I have created a database and used visual basic 2005.net2.0 to build the application. I used the data wizard. it created datatables and then I bound it to the contols on the form. The program is published to the server and each instance loads from the server and executes. When it stops, the instance is destructed from the host pc. The pc's are large ram and very small hard drive. These were the specs of the job. now when each pc loads an instance of the program, they can all load and edit the same exact record. I tried to bust it and I got on the same record and changed first name on one and last name on the other. the second one overwrote the first name edit. All of the data handling is done inside of the dataset designer and it does not allow edits. ( actually you can edit, but the next time you save it, or run it, it will rewrite what you added and it will be gone.) is there anything I can add to the form vb to tell it to lock the current record?

View 3 Replies View Related

SQL Server Row Locking

Jun 28, 2001

I have a table X with 61390 rows on it. IT is a crucial table which is being read and updated constantly. If I create a clustered index on the Primary Key (identity column) and run UPDATE x SET c1 = 1234 where PKCOL = 4321 the best lock I can get is a table Lock. If I create a compound non-clustered index on C1 and PKCOL the best lock I can get is a Page Lock. PAge Lock is OK but as this table is in High demand I want a row lock so others can carry on referenceing other parts of the table. WHy does it take a page lock and not a Row lock?

View 1 Replies View Related

Row Locking In SQL Server 7.0

Jul 7, 1999

Hi,

We are becoming increasingly more involved with SQL Server 7.0 development.
Can someone show me a good example of ROW LOCKING with exclusive and share
modes?
If I am starting a transaction with a SELECT and later an UPDATE, what is
the best way to handle locking?

Thank you for any help on this issue.
Steve

View 1 Replies View Related

Locking Cb On Server

Mar 6, 2007

is there a way of locking db on server. i am doing a overtime and pay system but there is a few members of IT staff that are very nosey and this is senstive information and i dont want them looking at the tables on the server can these be locked for only me to view

View 3 Replies View Related

SQL Server Locking

Mar 22, 2007

Hello,

I'm trying to determine if a row in a table is locked. First, I issue a lock on some rows. Then, I query the syslockinfo table to see which rows are locked. It tells me which rows are locked, but it returns a hashed resource value that, I guess, is somehow related to the key. How can I un-hash the value? Or, how can I hash my own key so that I can compare it with the hashed value? I have tried using the HashBytes function, but I don't know what is actually being hashed when the row is locked.

For example:

begin transaction

select * from test with (rowlock, updlock)

select * from master..syslockinfo

where rsc_objid = (select id from sysobjects where name = 'test') and req_mode = 4

returns:

rsc_text = (010086470766); rsc_bin = 0x000708001374FC020100010086470766

Thanks.

View 3 Replies View Related

Locking SQL Server

Apr 23, 2007

Hi



I have a setting where two Web Servers access the same SQL Server database. To gaurantee consistent data writes and reads I need to lock part of the database in special conditions.



I know exactly when I need particular tables of the database to be locked, but I am in doubt of how to do it. Does SQL Server 2005 have any mechanism for providing locks gauranteed to free the lock if one of the web servers crash - or if SQL Server itself crashes?



/Bezbos

View 1 Replies View Related

Record Locking In ADO.net/Sql Server

Feb 18, 2005

Currently I am working on asp.net Intranet system.I need some suggestion on records locking for Sqlserver & ASP.net.
I want to prevent two user to open the same record for modify.Means if some one has open one record (id=xxxxx) for modify then others should not be able to open same same record (id=xxxxx) for modify .otherwise if both user will open/update same record then information in database will not be updated correctly.
Any idea how we can do the record locking so that not two users can open same record(id=xxxxx) for modify.

Thanks in Advance
Arvind

View 2 Replies View Related

How Do I Do Row Level Locking In The Sql Server?

Apr 6, 2001

View 2 Replies View Related

Locking Problem: SQL Server

Jul 23, 2005

Hi All,According to my observation using SP_WHO2 in my database, some INSERTstatements are getting blocked by SELECT statements. Though theblockingSELECT statement is having ReadPast hint, i think, it will only readpastlocked resources but will not guarantee the select statement itself notblocking other statements(in my case Insert). According to my knowledgeandinformation, select statements take shared locks but why then thesestatements are blocking insert statements?Can there be any other solution other than using NoLock hint as thishintmake sure no shared locks are issued but it can read uncommited data.Need help urgently.ThanksRitesh

View 5 Replies View Related

SQL Server Locking Issues

Dec 8, 2006

How to avoid table locks during simultaneous addition, deletion and updates of 50,000 records or more. I am using SQL Server 2005 interfacing with Java.

Thanks,

View 2 Replies View Related

Sql Server Restart After Locking

Mar 27, 2007

Hi...

i hv a database (sql server 2000) where i got locking on many tables and my application was down.

I restarted the sql server and the application was fine but after five minutes the same locking issue started happening. I did a index rebuild the next time on all indexes and everything was fine.But i cannot relate how locking occured and why it was not after index rebuild.Can anyone shed some light on this or anyone had similar experience... cos i cannot figure out a way on this.

Thanks in advance

View 4 Replies View Related

A Few Questions On Locking In Sql Server 2005

Jan 29, 2008

Hi pardon my ignorance but I wonder if someone could answer a few questions for me.

I am writing a program which will be used by perhaps upto 100 users at a time. The program sits on any number of PCs and loads user specific data to a given PC according to who has logged on to windows on that PC.

A number of data items loaded from the user table have to be unique as they are usernames for other systems that my program simplifies access to.

So when a user logs on to my program for the first time a row is created for them in the user table (indexed by a GUID and their unique network name). The other unique fields are left blank and the user is given an opportunity to fill these details in.

Before writing these details to the user's row in the 'users table' the program loads the whole user table down and checks that these items are unique before committing them to that user's row in the table.

The problem of course is that if between the program downloading the user table into a local datatable, checking the values are unique and then actually writing them someone else writes the same data into their row then 2 users end up with the same data - which shouldn't be allowed. i.e. 2 users can't have the same user name for the other software.

How can I solve this problem with locking? Once the user table is downloaded and in a locel datatable presumably the table is no longer locked so another user could write data to the table.

I acutally think this is going to be a pretty rare occourance but I still want to try to cover all eventualities.

I suspect the problem is the way my program is going about the checking.

Should I use an SQL insert statement like??

If exists(SELECT username from users where username=@username)
BEGIN
RAISEERROR("Username already exists")
END
ELSE
BEGIN
INSERT etc

If so I guess this will simplify my code. Is this the correct thing to do? And then just trap the errors that arise if a duplicate does arise?

Also some more general questions.

1)I presume 2 users simultaneously looking up data from 2 different rows in a table doesn't lock the table so one search fails? I use the code below having set up a command to run a stored procedure to search for a user by their network name.

Dim lclRowRet As SqlDataReader

lclRowRet = LoadUserCommand.ExecuteReader(CommandBehavior.SingleRow)

lclRowRet.Read()

2) I presume writing data to my user table a row at a time will also not cause a lock. I create a command object with all the row values in and then do a command.executenonquery()

As a rule I close all my connections as soon as I'm done with them.

Many thanks for your help in advance.

nik

View 5 Replies View Related

SQL Server Express Is Locking The Database

May 9, 2006

I'm running a website on IIS 6.0 w. ASP.Net 2.0 and SQL Server Express 2005 via the native client. The connection string is fairly standard:

<add name="SiteSqlServer" connectionString="Data Source=.SQLEXPRESS;AttachDbFilename=c:DotNetNukeApp_DataASPNETDB.MDF;Integrated Security=True;User Instance=True" providerName="System.Data.SqlClient"/>

I find that after the website has been running for a while I can no longer open the database using SQL Server Management Studio Express (I get an error indicating that the physical file has been locked). Even if I shutdown and restart both IIS and SQL Server, it remains locked and can only be opened once I find and "End Process" all the sqlservr.exe instances from the Task Manager.

Is this a known issue? Any way to find out what is locking the database, or any specific configuration to check?

thanks
Steve

View 1 Replies View Related

Transact SQL :: Row Level Locking In Server

Apr 22, 2015

We have one table.We have updated the status for one column to 1 and we did not committed the transaction. Can we do an another update on another row.

In below example i am updating GEO_D and transaction is not committed. Now my requirement is we have to update other records (not Geo_D). If  try to update GEo_D it should wait. 

IF OBJECT_ID('TEMPDB..##TEMP_STSTUS') IS NOT NULL
DROP TABLE ##TEMP_STSTUS
CREATE TABLE ##TEMP_STSTUS
(
  ID INT IDENTITY(1,1)
  ,NAME VARCHAR(10)
  ,STSTUS VARCHAR(10)
)
INSERT INTO ##TEMP_STSTUS SELECT 'GEO_D','0'

[Code] ....

View 6 Replies View Related

SQL Server Phantom SPIDs Causes Locking And Delays

Nov 10, 2003

A fellow developer of mine has created a ASP.Net application that executes some fairly complex stored procedures. This application is for all intensive purposes a queue and 3 or 4 people work on processing items in a FIFO type environment. There is logic in the Stored procedures to make sure each worker get a unique entry using a series of query hints.

Well what we are seeing is if these works are moving at a rapid pace and we execute an sp_who2 on the sql server there are entries that that seems to be hanging there and REMAINING there even after a browser is closed or the disposed method has been called on the connection object. Has anyone else experienced something similar to this with an ASP.Net application used by mutiple people?

My inclination is to blame the design of the application, but before I do that and step on my co-workers toes I thought I would throw this out to the group.

Thanks in advance for your input.

View 7 Replies View Related

Row Level Locking And SQL Server 6.5 Compatibility Mode

Jan 5, 2001

I'm running SQL Server 7.0. I have a DB running with 6.5 compatibility mode.

Do INSERT, UPDATE or DELETE queries use row level locking in this DB ?

(I know if I set the db compatibility mode to 7.0 row level locking will be enabled)

Thanks in advance for your help.

View 1 Replies View Related

Change SQL Server Query Optimizer Locking

Dec 23, 2004

Hi,

Our app has been distributed on more then 300 different sites.
On one of the sites we get the error "Could not continue scan with NOLOCK due to data movement" indicating that the query optimizer takes a NOLOCK for our select statement ( has been opened with adOpenDynamic, adLockOptimistic ).

It's no option to change the source, we have to solve this without touching the code.

Is there any way to tweak the query optimizer so that our app works correctly?
I know that there will be a reduction of performance but it's our only choose.

thnx in advance,

adOpenDynamic, adLockOptimistic

View 4 Replies View Related

Quick SQL Server 2000 Locking Question

Nov 28, 2005

We are running a 3rd party ETL tool to populate a denormailized version of a production database for reports. Everything works fine 95% of the time. However there is a semi-rare occurence of the ETL tool hanging up. The norm is for the tool to take about 5 times longer than usual, but it still works. Over the weekend however it through an error saying:

The SQL Server cannot obtain a LOCK resource at this time. Rerun your statement when there are fewer active users or ask the system administrator to check the SQL Server lock and memory configuration.

The reports are run through Crystal using stored procs and are all basically select statements

So my question(s) are the following:
1. What kind of lock would a report put on a table (select statement)
2. Would it make sense to change stored procs to use WITH NOLOCK?
3. Or is something else going on?

Your thoughts would be greatly appreciated.

View 5 Replies View Related

SQL Server How To Prevent Locking To Do Read-Only Reports

Jul 20, 2005

Need some information regarding SQL Server locking.Requirement is to run SQL Statements for reports (read-only) that willnot lock-out other people trying to update (write lock). For this, wetried the following to make the db connection not deny write locks(our report code will not have a read-only lock).ADODB.ConnectionObj.Mode =adModeShareDenyNoneBut this made our connection bumped whenever someone tried to update.Tried enabling dirty reads by doing:ADODB.ConnectionObj.IsolationLevel =adXactBrowseEven this made our connection bumped whenever someone tried to update.Is there a way to achieve what is needed without having a seperatedatabase for reports?

View 1 Replies View Related

Locking Up After SQL Server Mobile Merge Replication

Nov 17, 2005

Hi,

View 14 Replies View Related

Locking Up After SQL Server Mobile Merge Replication

Nov 9, 2007



Hi ,
I would like to get your advice in an issue that I am facing regarding merge replication.
The flow is like:
1) User enter his login name and password.
2) Host_name is set as the login name that the user enters.
3) Based on the HOST_NAME property after filtering user gets the records relevent only to him
(Differnet subscriber may use same mobile device).

4) He make some changes in the local sdf according to the business logic.
5) The application Syncs with server on the next login session.

My issue is when I am trying to run the application in emulator exactly at the sdf updating part the application terminates.
Error mess: Connection to Remote Device has been lost.....
If I execute the same sql insert query it works om the local sdf and master database.
Emulator used where Pocket PC 2003 SE and Windows Mobile 6 classic emulator.
I have installed 1) Visual Studio 2005 SP 1 2) net compact framework SP2.

When I comment all the code related to Sync ,application works witout any issue.
And the same application works in my "I mate kjam".

The code that I use is given below:
==========================================================================

public void Sync(string hostname, int newsub) // Parameters for HOSTNAME and flag to denote new user or existing //user.

{

SqlCeReplication repl = new SqlCeReplication();

repl.InternetUrl = @"http://231.000.000.211/Merge/sqlcesa30.dll";

repl.Publisher = @"SERVER";

repl.PublisherDatabase = @"Merge";

repl.PublisherSecurityMode = SecurityType.DBAuthentication;

repl.PublisherLogin = @"sa";

repl.PublisherPassword = @"password";

repl.Publication = @"Merge";

repl.Subscriber = @"MergeSub";

repl.HostName = hostname;







repl.SubscriberConnectionString = @"Data Source=""Program FilesMerge.sdf"";Max Database Size=128;Default Lock Escalation =100;";





try

{

if (newsub == 0)

{

if (File.Exists(@"Program FilesMerge.sdf"))

{

File.Delete(@"Program FilesMerge.sdf");

}



repl.AddSubscription(AddOption.CreateDatabase);

repl.Synchronize();

repl.Dispose();

MessageBox.Show("newuser sync Done");

}

else

{

if (!File.Exists(@"Program FilesMerge.sdf"))

{

repl.AddSubscription(AddOption.CreateDatabase);

repl.Synchronize();

repl.Dispose();

MessageBox.Show("FirstSync Done");

}

else

{

repl.Synchronize();

repl.Dispose();

MessageBox.Show("SameuserSync Done");

}

}

=================================================================================
Please advise......

View 1 Replies View Related

SQL Server 2008 :: Parent Records Ordering And Display Child Records Next To It?

Sep 7, 2015

declare @table table (
ParentID INT,
ChildID INT,
Value float
)
INSERT INTO @table
SELECT 1,1,1.2

[code]....

This case ParentID - Child 1 ,1 & 2,2 and 3,3 records are called as parent where as null , 1 is child whoose parent is 1 similarly null,2 records are child whoose parent is 2 , .....

Now my requirement is to display parent records with value ascending and display next child records to the corresponding parent and parent records are sorted ascending

--Final output should be

PatentID ChildID VALUE
33 1.12
null3 56.7
null3 43.6
11 1.2
null1 4.8
null1 4.6
22 1.8
null1 1.4

View 2 Replies View Related

I Want To Transfer ONLY New Records AND Update Any Modified Records From Oracle Into SQL Server Using DTS

Jul 23, 2005

I need a little help here..I want to transfer ONLY new records AND update any modified recordsfrom Oracle into SQL Server using DTS. How should I go about it?a) how do I use global variable to get max date.Where and what DTS task should I use to complete the job? Data DrivenQuery? Transform data task? How ? can u give me samples. Perhaps youcan email me the Demo Package as well.b) so far, what I did was,- I have datemodified field in my Oracle table so that I can comparewith datelastrun of my DTS package to get new records- records in Oracle having datemodified >Max(datelastrun), and transferto SQL Server table.Now, I am stuck as to where should I proceed - how can I transfer theserecords?Hope u can give me some lights. Thank you in advance.

View 2 Replies View Related

Server Locking Up Everytime A DBCC DBREINDEX Is Issued

Apr 6, 2001

Every time I execute DBCC DBREINDEX (Table_Name, '',0)WITH NO_INFOMSGS the server hangs. No error messages in windows 2000 logs or in the SQL 7.0 logs.

The table is about 2 gig in size and the index is a clustered index on two fields.

The server has 1 gig of memory and the cache hit ratio, and cache flushes both look good. Any ideas? Any help would be greatly appreciated.

View 2 Replies View Related

SQL Server 2014 :: Minimizing Locking On Update Statements?

May 4, 2015

I have a main table called Stock for example.

One process ( a service ) inserts data into this table , as well as updates certain fields of the table periodically.

Another process ( SQL Job ) updates the table with certain defaults and rules that are unknown to the service - to deal with some calculations and removal of null values where we can estimate the values etc.

These 2 processes have started to deadlock each other horribly.

The SQL Job calls one stored procedure that has around 10 statements in it. This stored proc runs every minute. Most of them are of the form below - the idea being that once this has corrected the data - the update will not affect these rows again. I guess there are read locks on the selecting part of this query - but usually it updates 0 rows - so I am wondering if there are still locks taken ?

UPDATE s
SET equivQty = Qty * ISNULL(p.Factor,4.5) / 4.5
FROM Stock s
LEFT OUTER JOIN Pack p
on s.Product = p.ProductId
AND s.Pack = p.PackId
WHERE ISNULL(equivQty,0) <> Qty * ISNULL(p.Factor,4.5) / 4.5

The deadlocks are always between these statements from the stored procedure - and the service updating rows. I can't really see how the deadlocks occur but they do.

Another suggestion has been to try and use an exists before the update as below

IF EXISTS( SELECT based on above criteria )
( UPDATE as before )

Does this reduce the locking at all ? I don't know how to test the theory - i added this code to some of the statements, and it didn't seem to make much difference ?

Is there a way to make a process ( in my case the stored procedure ) - give up if it can't aquire the locks rather than being deadlocked - which leads to job failures and emails etc ?

We are currently trying to filter down the data that is updated to be only the last few months - to reduce the amount of rows even analyzed - as the deadlocking does seem to be impacted by the number of rows in the tables.

View 9 Replies View Related

SQL Server 2012 :: Extract Locking Information In Database

Jul 16, 2015

I am using following sql to extract locking information in database. It only work on current selected database, how can I tune to work on all databases and not only currently selected?

SELECT DISTINCT
ES.login_name AS LoginName,
L.request_session_id AS BlockedBy_SPID,
DATEDIFF(second,At.Transaction_begin_time, GETDATE()) AS Duration_Sec,
DB_NAME(L.resource_database_id) AS DatabaseName,

[Code] ....

View 3 Replies View Related

SQL Server 2014 :: Table Locking While Insert Statement

Sep 18, 2015

I have two tables for insertion in one transaction scope. Table one have 10 rows. After first table insert statement (not yet committed) if I run select on first table from other session, it holds table until my insert is committed or rolled back and from (SSMS), it display 10 rows and then wait for transaction scope till finished. My question is do I need to use no lock hint in this situation. Or there is something wrong with isolation level. One saying that in this situation table should not hols select while insert is in transaction scope.

View 5 Replies View Related

Linked Server Error... Openquery() Locking Tables

Feb 1, 2008



Hi All -

My Set up:

Server A - Oracle 10g Database
Server B - SQL2005
Client PC - Sql Express

Server A holds all data. I am using a linked server to connect server A and B. I use a set of stored procedures containing the openquery() syntax to get data from Server A to Server B. These stored procedures run every 20 minutes. I then create a publisher on Server B. I subscribe from the client PC to publisher to get data down from Server B to client(Download only subscription).

When I fire up the stored procedures and attempt to replicate, everything works fine. It appears after about 4-5 hours of the stored procedures running replication begins to hang more and and more until eventually it hangs for about 10 minutes and I recieve the following error:

Command attempted:
{call sp_MSreleasemakegenerationapplock}
Error messages:
The merge process was unable to create a new generation at the 'Publisher'. Troubleshoot by restarting the synchronization with verbose history logging and specify an output file to which to write. (Source: MSSQL_REPL, Error number: MSSQL_REPL-2147200994)

I'm not sure if there is an error with openquery() locking? There is some locking activity going on with the TempDB and and Server B database. I've also come across some threads talking about the agent profiles. I'm very new to replication and very confused by all of the options in the agent profiles. Any help would be greatly appreciated!

View 1 Replies View Related

SQL Server Admin 2014 :: Inserts Causing Locking In Production DB

Apr 2, 2015

I have a production DB that all of a sudden it seems that any and every insert causes massive locks/blocks.

If I kill the offending spid anther spids pops up with the block/lock.!

View 7 Replies View Related







Copyrights 2005-15 www.BigResource.com, All rights reserved