[英]Database trigger or application code? which one should I use in this case?
Using c# and mssql 2008 R2, I have a service that inserts a user into the system, users have a unique number assigned to them which is something like a1, b1 or c1 which will get increased on user insertion but before insertion I have to check whether there is any previous unique number available or not( unique numbers can be deleted on user deletion). 使用c#和mssql 2008 R2,我有一个将用户插入系统的服务,为用户分配了一个唯一的编号,例如a1,b1或c1,这在用户插入时会增加,但是在插入之前,我必须检查是否有以前的唯一编号可用(可以在删除用户时删除唯一编号)。 For example if there are 5 users in the database, a1,...,a5 are reserved and if you delete lets say 3rd user then a3 will be available for next user insertion.
例如,如果数据库中有5个用户,则保留a1,...,a5,如果您删除说第三个用户,则a3将可用于下一个用户插入。 This can be done easily but since I have to read the available unique numbers on every insertion , I'm puzzled whether it's better to use insert trigger or use application code before insertion ?
这很容易做到,但是由于我必须在每次插入时都读取可用的唯一编号,所以我对在插入之前使用插入触发器还是使用应用程序代码会更好感到困惑。
Thanks in advance 提前致谢
I'm not sure about triggers and how you want to do it this way but you can definitely achieve that in the code/stored proc. 我不确定触发器以及您如何以这种方式进行操作,但是您绝对可以在代码/存储过程中实现它。 This will be a 2 step process that will have to be in one transaction:
这将是一个两步过程,必须在一个事务中进行:
One important thing is that you will want to lock the table during the select query to prevent other processes obtaining the same ID. 重要的一点是,您将需要在选择查询期间锁定表,以防止其他进程获取相同的ID。 You can do that using exclusive lock hint.
您可以使用排他锁提示来做到这一点。 The code might look like:
该代码可能类似于:
select min(T.ID) + 1 from TableName T with(xlock)
where not exists (select * from TableName T1 where T1.ID = T.ID + 1)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.