0

I have a SQL Server database, multi-user can insert to it.

But for many reasons, I want only 1 user can insert at a time.

Example: User 1 want to insert 100 record, while user 1 is inserting (100 record not saved to table). Other user can not insert to the table.

I have thought to use a flag, but I want to find another way.

Is there any SQL statement that can do that?

Thanks for reading!

user12486851
  • 61
  • 1
  • 7

2 Answers2

0

For that purpose you can used table lock or row loack concept.

ALTER TABLE Table_name SET (LOCK_ESCALATION = < TABLE | AUTO | DISABLE > –One of those options)

For more details you can also visit this link locking in SQL Server

0

It seems that you need to use

INSERT INTO TABLE with (rowlock)

Read the following post to have a better understanding.

Using ROWLOCK in an INSERT statement (SQL Server)

Updated

SQL supports us to handle 1 record at a time e. And your case is to want multiple records to handle serialized format.

I think the best you put into the temp table, there is a window service running real-time (Background service: using quartz job or hangfire): insert and delete then the temporary table with a column named IsInserted.

Nguyễn Văn Phong
  • 13,506
  • 17
  • 39
  • 56
  • No, I write a while loop to insert with rowlock/tablock. And I try to insert 1 row by SQL Server Management Studio, and it have insert success. So, rowlock didn't working? – user12486851 Feb 07 '20 at 09:13
  • How can you make sure that you are inserting at a time? – Nguyễn Văn Phong Feb 07 '20 at 09:15
  • Cho phép em viết Tiếng Việt nhé, theo ý anh là vòng lặp while nó không thực sự insert dữ liệu trong cùng lúc, mà giữa các lần insert có khoảng thời gian trống phải không ạ? – user12486851 Feb 07 '20 at 09:23
  • Vấn đề của em ví dụ như: 1 người dùng cần insert 100 dòng dữ liệu, và trong khi 100 dòng đó chưa được insert xong thì không người dùng nào khác được thực hiện insert. – user12486851 Feb 07 '20 at 09:26
  • Em cũng có nghĩ tới dùng cờ rồi. Nhưng không rành sql, nghĩ sql nó có cách handle nên lên hỏi thử :p. Em cảm ơn anh! – user12486851 Feb 07 '20 at 09:41
  • Thì sql hỗ trợ mình xử lý 1 record tại 1 thời điểm đó e. Còn trường hợp của mình là muốn nhiều records xử lý dạng tuần tự. Anh nghĩ tốt nhất em đưa vào bảng tạm, có một window service chạy real time (Background service: dùng **quartz job** hoặc **hangfire**): insert xong thì xóa hoặc bảng tạm có cột tên **IsInserted** – Nguyễn Văn Phong Feb 07 '20 at 10:33
  • I've just updated my answer with more details. Please take a look at @user12486851 – Nguyễn Văn Phong Feb 07 '20 at 10:36
  • 1
    You're so kind. Thanks for the right answer with awesome idea! That's what I need. But I haven't enough 15 reputation to vote up your answer :(. Again, thank you so much! – user12486851 Feb 08 '20 at 07:15