Data in SQL Server tables is not read repeatedly under multithreading

Source: Internet
Author: User

In some of the business, such as sending text messages, mail, we often use a table to store the data to be sent, from the background multiple threads constantly read from the table to send data to send, the completion of the transfer of data to the history table, so that the data to send the table is generally not too much. If the table structure to be sent is:

Create Table SMS (ID int NOT null identity (), Content varchar (1024x768), Status int not null,createtime datetime);

Status Value: 0 Unread 1 Read

The advantage of this design is that the backend will not be sent too slow to cause the front-end to receive the request to send a message, such as the business of sending SMS, sometimes due to the operator's gateway to send too slow, so that the front-end can first send the user's request to send all the table, the backend to slowly send.

Typically used in back-end send processes

Select top the From SMS Where status=0; SQL takes out the data that was not read.

In order to improve the back-end sending capability, multiple processes need to be deployed to send data from the table to be sent, which can sometimes cause the same record to be fetched simultaneously by multiple processes and sent.

Today, we looked at the MSDN of SQL Server and found that it was possible to ensure that each record was read only once by updating it at the same time through the deleted table (as if it were used in a trigger).

Declare @Rowid table (Rowid int);
BEGIN
SET ROWCOUNT 100; --Number of rows read at one time
--record status updates to be read first
Update Sms Set [status]= 1 output deleted.id into @Rowid Where [status] = 0;
--Read the record of the newly updated state
SELECT * from Sms where ID in (select Rowid from @Rowid);
END

Data in SQL Server tables is not read repeatedly under multithreading

Related Article

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.