Implementation (concurrent data processing) that is not obtained by other users)

Source: Internet
Author: User
Tags rowcount

Data obtained by one user is not obtained by other users:

Problem:

When using ADO to access the database, take a certain record (such as 20 rows) from a table and use it in the program, delete records after use (no need to update or delete records ). In multi-user operations (each user uses the same operation), how can we ensure that the records selected by one user are not selected by other users?

Solution:

To solve this problem, you can add a flag column and set a flag for each user's record. New users can only retrieve records from records whose flag is not retrieved.

In this article, we will use transactions and locks to control data processing without adding any flag columns.

Example:

1. Create a test environment

Use tempdb
Go
Create Table DBO. Tb (
Id int identity (1, 1 ),
Name nvarchar (1, 128 ))
Insert Tb (name)
Select Top 100
Name
From syscolumns
Go

2. Simulate 1st users

-- The query window sends the following query statement

Begin tran

-- The transaction is not committed or rolled back to keep the lock from being released

Set rowcount 20
Select *
From TB with (updlock, readpast)

-- Updlock keeps the lock until the end of the transaction. readpast skips the locked data.

3. Simulate 2nd users (the statement is the same as that of 1st users, but is executed in another connection)

-- The query window sends the following query statement

Begin tran

-- The transaction is not committed or rolled back to keep the lock from being released

Set rowcount 20
Select *
From TB with (updlock, readpast)

-- Updlock keeps the lock until the end of the transaction. readpast skips the locked data.

4. Results

You can see that query window 1 lists the first 20 data records, and query window 1 lists 21-40 data records.

In this case, different users need to fetch different data.

Note: After processing is complete, delete the record and submit the transaction.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.