How to avoid shared locks when validating foreign keys?

I have a table with a FK and I want to update a row in that table without being blocked by another transaction which is updating the parent row at the same time. Here is an example:
CREATE TABLE dbo.ParentTable
PARENT_ID int NOT NULL,
VALUE varchar(128) NULL,
CONSTRAINT PK_ParentTable PRIMARY KEY (PARENT_ID)
GO
CREATE TABLE dbo.ChildTable
CHILD_ID int NOT NULL,
PARENT_ID INT NULL,
VALUE varchar(128) NULL,
CONSTRAINT PK_ChildTable PRIMARY KEY (CHILD_ID),
CONSTRAINT FK_ChildTable__ParentTable FOREIGN KEY (PARENT_ID)
REFERENCES dbo.ParentTable (PARENT_ID)
GO
INSERT INTO ParentTable(PARENT_ID, VALUE)
VALUES (1, 'Some value');
INSERT INTO ChildTable(CHILD_ID, PARENT_ID, VALUE)
VALUES (1, 1, 'Some value');
GO
Now I have 2 transactions running at the same time:
The first transaction:
SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED;BEGIN TRAN
UPDATE ParentTable
SET VALUE = 'Test'
WHERE PARENT_ID = 1;
The second transaction:
SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED;BEGIN TRAN
UPDATE ChildTable
SET VALUE = 'Test',
PARENT_ID = 1
WHERE CHILD_ID = 1;
If 'UPDATE ParentTable' statement runs a bit earlier, then 'UPDATE ChildTable' statement is blocked untill the first transaction is committed or rollbacked. It happens because SQL Server acquires shared locks when validating foreign keys, even
if the transaction is using read uncommitted, read committed snapshot (read committed using row versioning) or snapshot isolation level. I cannot see why change in the ParentTable.VALUE should prevent me from updating ChildTable. Please note that ParentTable.PARENT_ID
is not changed by the first transaction, which means that from FK's point of view whatevere is set to the ParentTable.VALUE is never a problem for referential integrity. So, such blocking behavior seems to me not logical. Furthermore, it contradicts to the
MSDN:
Transactions running at the READ UNCOMMITTED level do not issue shared locks to prevent other transactions from modifying data read by the current transaction. READ UNCOMMITTED transactions are also not blocked by exclusive locks that would prevent the
current transaction from reading rows that have been modified but not committed by other transactions. 
Does anybody know how to workaround the issue? In other words, are there any tricks to avoid shared locks when validating foreign keys? (Disabling FK is not an option.) Thank you.
Alexey

If you change the primary key of the parent table to be nonclustered, there is no blocking.
Indeed, when I update ParentTable.VALUE, then:
in case of PK_ParentTable is clustered, a particular row in the clustered index is locked (request_mode:X, resource_type: KEY)
in case of PK_ParentTable is non-clustered, a particular physical row in the heap is locked (request_mode:X, resource_type: RID).
and when I update ChildTable.PARENT_ID, then:
in case of PK_ParentTable is clustered, this index is used to verify referential integrity:
in case of PK_ParentTable is non-clustered, again this index is used to verify referential integrity, but this time it is not locked:
It is important to note that in both cases SQL Server acquires shared locks when validating foreign keys. The principal difference is that in case of clustered PK_ParentTable the request is blocked, while for non-clustered index it is granted.
Thank you, Erland for the idea and explanations.
The only thing that upsets me is that this solution cannot be applied, because I don't want to convert PK_ParentTable from clustered to non-clustered just to avoid blocking issues. It is a pity that SQL Server is not smart enough to realize that:
ParentTable.PARENT_ID is not changed and, as a result, should not be locked
ChildTable.PARENT_ID is not actually changed either (old value in my example is 1 and the new value is also 1) and, as a result, there is no need at all for validating the foreign key.
In fact, the problem I described is just a tip of the iceberg. The real challenge is that I have deadlocks because of the FK validation. In reality, the first transaction has an additional statement which updates ChildTable:
SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED;
BEGIN TRAN
UPDATE ParentTable
SET VALUE = 'Test'
WHERE PARENT_ID = 1;
UPDATE ChildTable
SET VALUE = 'Test'
WHERE PARENT_ID = 1;
The result is famous message:
Msg 1205, Level 13, State 51, Line xx
Transaction (Process ID xx) was deadlocked on lock resources with another process and has been chosen as the deadlock victim. Rerun the transaction.
I know that if I change the order of the two statements, it will solve the deadlock issue. But let's imagine I cannot do it. What are the other options?
Alexey

Similar Messages

  • How to avoid ModelLayer Update when validation fails in ValueChangeListener

    Hi,
    One of the requirement in my application is to avoid model layer update when a value is changed in a field and it is not a valid value according to business functionality. Scenario is explained below.
    1. Screen has one field SSN no.
    2. User enters 889787873 (According to functionality, SSN no. should not start with 8 or 9)
    3. The moment user enters and does Tab out, Value change listener gets fired (AutoSubmit is set to true and value change listener is mapped to it)
    4. I have a util method isValidSSN(int ssnNo) that gets the SSN no as input argument, validates it, returns true if it is valid otherwise false.
    There can be many ways to achieve the above said functiontlity including the best way of keeping the validation at entity attribute level. But that is not what i am looking for. I am doing migration of desktop application and want to mimic the code as how as it is (According to client requirement).
    Requirement behavior:
    In value change listener, I should get the newly entered value (Not from ValueChangeEvent.getNewValue()), validate it. If it is valid, I should update the model. If not, I should not do model layer update call at all as i want to keep my transaction undirty, but show invalid SSN message to the user.
    Requirement:
    1. Get the new value inside valueChange listener. I don't want to use valueChangeEvent.getNewValue() because what i said as SSN is just an example but in our app, we use many data types including custom domain data types. So i cannot expect valuechangeEvent.getNewValue() always gives me the new value with proper data type. I also know i cannot use UiComponent.processUpdate(facesContext) to get the new value from VO attribute. Because calling processUpdate issues setAttribute call at model layer, which in turn makes the transaction dirty. So i need to access the newly entered value with proper data type in some other way.
    2. If any itemChange logic fails, I should not update the model layer but directly comes to render response. I hope this is doable by calling FacesContext.renderResponse() API but need confirmation or any other way if i am wrong.
    Thanks in Advance.
    Raghu

    Thanks to all for your responses. Regarding accessing of new value inside value change listener, I am sure ValueChangeEvent.getNewValue() is not going to give me the value with proper data type. I am not using immediate attribute anywhere but use custom domain data type with masking (i.e. Formatter Format). Also I use InputDate field. Always valueChangeEvent.getNewValue() gives me the string representation of the value but not with actual data type.
    Question:
    1. Is there any API, that gets the valueChangeEvent.getNewValue() and the UI components as parameters and return the data with proper data type?
    2. I need to get the newly value with proper data type inside valueChangeListener. Is it achievable? If so, how?
    Need your help.

  • How to avoid the dialogue when converting from context menu

    This is a follow-up to http://forums.adobe.com/message/2016146#443364 which was locked due to a bug.
    i would like to know how i can avoid the 'save as' dialogue when using the context menu to convert a word file to pdf using windows XP/acrobat 8/word 2007.
    so far, it always prompts me for the filename, which is annoying as it does not allow me to batch-convert several files and let the thing run its course.
    the solution provided by Steve in the other thread does not work - even if the plugin from word does not propt for a filename, it still does when triggered from explorer/context menu.
    so back to square one: how to avoid that dialogue when not opening word at all?
    cheers, thanks for any help. michael

    For a permanent change, START>PRINTERS>right click on Adobe PDF printer and select properties>General>Printing Preferences>Adobe PDF Settings. Under the settings tab, uncheck the box related to asking for a name. Pretty sure that is the location, but it may vary with version.

  • How to create shared lock

    Hi,
    Can any please tell me how create a shared lock in steps.
    Thanks in advance
    Priya

    Hi Swati,
    This may not be possible, because you have created shared lock for the four different views but the table is one.
    So when one is editing then definitely if the other try to access the same entries then the object will be locked.
    First understand how and which lock can do which type of action.
    For your assistance read this and try to find the answer.
    Exclusive lock
    The locked data can be read or processed by one user only. A request for another exclusive lock or for a shared lock is rejected.
    Shared lock
    Several users can read the same data at the same time, but as soon as a user edits the data, a second user can no longer access this data. Requests for further shared locks are accepted, even if they are issued by different users, but exclusive locks are rejected.
    Exclusive but not cumulative lock
    Exclusive locks can be requested by the same transaction more than once and handled successively, but an exclusive but not cumulative lock can only be requested once by a given transaction. All other lock requests are rejected.
    Cheers!!
    VEnk@

  • How to avoid launching Labview when invoking VI by Teststand

    Hi, friends.
    I'm a learner of teststand. I wrote some VIs by Labview. Now I want to invoke them in teststand environment. But when I run the sequence. Labview will be automatically launched. How to avoid launching Labview when I run the sequence?
    Thanks.
    Solved!
    Go to Solution.

    I'm not sure that I follow what you are saying..  But it sounds like when the VI is called, the LabVIEW development software is started and you want to avoid that.
    If you create an executable or dll and call that from within TestStand, it should not call the development environment.  You would need to have the LabVIEW run-time engine installed on the target PC. 
    It has been many years since I've used TestStand with LV, so my memory may not be accurate.  I think the above had worked for me.  However, it seems that I recall something about having the LV code in debug mode causing it to open the development environment.... but it's a distant memory.    You're not using breakpoints where the LV VI is being called, are you?
    R

  • How to avoid data repetation when using select statements with innerjoin

    how to avoid data repetation when using select statements with innerjoin.
    thanks in advance,
    satheesh

    you can use a query like this...
      SELECT DISTINCT
             frg~prc_group1                  "Product Group 1
             frg~prc_group2                  "Product Group 2
             frg~prc_group3                  "Product Group 3
             frg~prc_group4                  "Product Group 4
             frg~prc_group5                  "Product Group 5
             prc~product_id                  "Product ID
             txt~short_text                  "Product Description
    UP TO 10 ROWS
    INTO TABLE l_i_data
    FROM
    Joining CRMM_PR_SALESG and
    COMM_PR_FRG_ROD
    crmm_pr_salesg AS frg
    INNER JOIN comm_pr_frg_rod AS prd
    ON frgfrg_guid = prdfragment_guid
    Joining COMM_PRODUCT and
    COMM_PR_FRG_ROD
    INNER JOIN comm_product AS prc
    ON prdproduct_guid = prcproduct_guid
    Joining COMM_PRSHTEXT and
    COMM_PR_FRG_ROD
    INNER JOIN comm_prshtext AS txt
    ON prdproduct_guid = txtproduct_guid
    WHERE frg~prc_group1 IN r_zprc_group1
       AND frg~prc_group2 IN r_zprc_group2
       AND frg~prc_group3 IN r_zprc_group3
       AND frg~prc_group4 IN r_zprc_group4
       AND frg~prc_group5 IN r_zprc_group5.
    reward it it helps
    Edited by: Apan Kumar Motilal on Jun 24, 2008 1:57 PM

  • How dose family sharing work when one person wants to use a gift card?

    How dose family sharing work when one person wants to use a gift card?

    kokogo,
    Purchases made in the iTunes and App Stores will first attempt to use any store credit that exists on the purchaser's account. Barring sufficient credit, the family organizer's card will be used for the purchase.
    First, their store credit will be used to pay the partial or total bill. The remainder will bill to the family organizer's card. As the family organizer, any receipts generated by the transaction will be sent to you. Learn more about how iTunes Store purchases are billed.
    Family purchases and payments
    https://support.apple.com/en-us/HT201079
    Sincerely,
    Allen

  • How to avoid safety warning when opening a pdf from an link in another pdf?

    I make pdf in Acrobat with links to other pdf files av have made. When i try to click a link to open the pdf, i get the safety question if trust it or if i will block it. How to avoid that question all the time?

    Hello Kvalitetetsansvarlig
    Try adding the PDF to the trust location in Acrobat
    Edit -> Preferences-> Security (Enhanced), Click on "Add File", and browse to your file.
    Click on "OK" button and check.
    Regards,
    Deepak

  • How to prevent shared locks in SELECT statement?

    Hi,
    In SQL Server we can use (NOLOCK) to prevent shared locks on each row:
    Select * from table (NOLOCK)
    Do we have similar technique for oracle so it doesn’t consider a shared lock for each returned row?
    Thank you,
    Alan

    Yes - it's called a query ;-)
    Oracle was designed with a 'consistent read' mechanism that guarantees that a query will see the image of the data at the moment when the query started, regardless of the number of updates (including deletes) that have occurred since the query started. This is done using the rollback (aka undo) segment. Flip side - there is no such thing as a 'dirty read'.
    Because of the implementation, a simple select or subselect without coersion (such as the 'FOR UPDATE' clause) will not block writers, nor will writers (updates/inserts/deletes) block readers.
    In addition, an update in Oracle will only lock the rows affected by the update, there is no escalation of locks needed (or possible), and commits do not introduce any 'lock clearing' overhead.
    The penalties for all of this
    - the rollback segment must be sized appropriately or you end up with ORA-01555 errors;
    - you should not commit in loops, especially not loops controlled by a cursor;
    - code written to be efficient in SQL Server is often inefficient in Oracle, and vice versa.
    Recommended reading is Tom Kyte's book at http://www.apress.com

  • How to Implement shared lock

    Hi friends,
    For a table I have created views. I want to create shared lock for that table.
    How to achieve that.
    can we create shared lock for views?
    Thanks.

    Hi Pagidala,
    Go to Se11-> Select Lock object radiobutton->give some name starting with E for example EZDEMO_LOCK->click on Create ->give short description->clcik on Tables Tab->give the table name for which you want to implement shared lock example ZTABLE ->lock mode you select as Read Lock.After this save check and activate your lock object.
    We have selected READ LOCK since it protects read access to an object. The read lock allows other transactions read access but not write access to the locked area of the table.
    Check the below link for the complete information on Lock Concept.
    http://help.sap.com/saphelp_nw04/helpdata/en/41/7af4c5a79e11d1950f0000e82de14a/content.htm
    Cheers!!
    VEnk@
    Edited by: Venkat Reddy on Oct 29, 2008 11:54 AM

  • How to avoid clear record when tab pages changes

    Hi All
    I am using oracle forms 10g and db 10g.
    I have created a form with four tab pages. Namely "EXPENSE" , "AMOUNT_DETAILS", "SUPPLIER" , "ACCOUNT".
    When i enter a data in page 1 ie Expense and move to next page page2 "AMOUNT_DETAILS", and enters data in page3 "SUPPLIER" and when i come back to page1 "EXPENSE" and also Page2 "AMOUNT" the data get cleared in Tab pages. There is no data again i need to enter the data manually.
    Can any one suggest me how to avoid this clear data.
    Thanks & Regards
    Srikkanth

    Hi,
    Thanks once again for your quick response.
    I have checked it , i was working with oracle apps.Now i have entered all the datas in the four tab and press save button in the screen at that time also the data get cleared.Can you please tell is there any work around for this.
    regards
    Srikkanth

  • How to avoid the prompt when verifing signature?

    I sign the doc with my cert.
    The cert is not trusted by Acrobat/Reader itself so when i try to verify the signature Acrobat/Reader will prompt the user cert is not trusted.
    My question is how to avoid this prompt through Acrobat SDK or how to add my cert to trusted cert list through Acrobat SDK?
    Thanks.

    Patrick Leckey wrote:
     You will also see the BER Decoding error when you have a self-signed peer-to-peer cert in your Windows Cert Store, even if it is not the signature you are using to sign.
    Start > Run > certmgr.msc
    Look for any certs that have "peer-to-peer" in the Intended Purpose column
    Remove that cert
    Restart Acrobat
    Give that a shot.
    Patrick,I have not found the Intended purpose of cert names "peer-to-peer".
    But I have just found the cert which will cause the signature failure.
    The key is the cert can not be removed.
    I'm very curious that why a cert has no relationship with the signature could cause the signature failure?
    Is it a BUG of Acrobat/Adobe Reader?
    If not how can i operate successfully?
    Thanks.

  • How to avoid opening photos when connecting a camera

    how can I avoid opening photos when connecting a camera?

    Connect the Camera.
    Launch Image Capture (in the Applications Folder)
    You can set what happens when you connect this device in the lower left of the Image Capture window.

  • How to avoid water damage when installing invisible shield

    Just wondering what you have to do to avoid water damage when installing Zagg invisible shield? What precautions should I take so that I do not damage the iPhone when installing Zagg Invisible shield?
    Thanks and I look forward to your replies.
    ...B

    Hi BGmail,
    I would stay away from invisible shield by zagg or similar products. I tried it, waste of £15, could have got myself a dock stand for my phone for that ****!! The problem with IS(invisible shield) is that the screen protector has a rubber feel which makes it annoying when swiping your finger on it + it's not scratch proof at all!! Mine scratched 2 days after the installation so badly that I had to remove it. The back it's hard to apply, does not cover everything you'd like to, also a dust trap that could get between tha film and the phone causing it to scratch, some people reporting the film going yellow after a while(on white iPhones).
    What I think of IS: A poor american product heavily/aggressive advertised!! Mine is off, using a hard clear plastic shell and a good screen protector, might look bulky but it's safe, only using the shell while at work, the iPhone is pretty tough, don't forget.
    Your choice... Good luck !!

  • How to avoid system slow when login first time  everyday

    if login system first time every day, it will be very slow for loading web application.
    I think maybe it 's  reload cache every night or by a certain perods of time.
    how to avoid this situation. or set cache reload a time per week?
    Thanks.

    Terry,
    I would confirm your application pools are set up as suggested in the install documentation.  This should resolve your issue.
    Thanks,
    Drew

Maybe you are looking for

  • Upload Sales Historical Data in R/3?

    Hi Guys: We are planning to use forecased based planning MRP Procedure ( MRP Type VV ) for Material Planning , we need historical sales data to execute the forecast. can anybody tell me step by step how to upload 12 months historical data into SAP R/

  • Problem in Customer Master data

    Hio friend I need some examples what type of problems or issues or ticket comes at clients in Customer Master data maintenance. If possible send some scnerios with solution also how it was solved. Thanks Raj

  • [Solved][Python 3] How to center tkinter window?

    Hi. I need to center window on the screen. The window that already has some contents like labels and buttons. Found this code snippet on Stack Overflow: w = root.winfo_screenwidth() h = root.winfo_screenheight() rootsize = tuple(int(_) for _ in root.

  • Why Do I Get "Unknown" Publisher?

    I am wondering why I always get an "unknown publisher" every time that I try to install the Java EE 6 SDK on my Windows 7 64-bit system?? I always get "Oracle" as the pubisher when I first install the Java Standard Edition SDK. What goes wrong in the

  • Integrated weblogic server in jdeveloper

    Starting WLS with line: C:\oracle\MIDDLE~1\JDK160~1\bin\java -client -Xms256m -Xmx512m -XX:CompileThreshold=8000 -XX:PermSize=128m -XX:MaxPermSize=512m -Dweblogic.Name=DefaultServer -Djava.security.policy=C:\oracle\MIDDLE~1\WLSERV~1.3\server\lib\webl