简体   繁体   English

数据库触发器或应用程序代码? 在这种情况下,我应该使用哪一个?

[英]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: 这将是一个两步过程,必须在一个事务中进行:

  • select the minimum available ID 选择最小可用ID
  • insert the new record 插入新记录

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.

相关问题 小型网络应用程序应使用哪个数据库 - Which Database should I use for small network application 我应该使用哪个框架和数据库? - Which framework and database should i use? Pushlet,长轮询或轮询-在聊天应用程序中应该使用哪一个? - Pushlet, Long polling or polling - Which one should I use in my chat application? 对于Winform应用程序,我应如何在另一台计算机上使用一台SQL计算机的数据库? - how should i use database of one sql machine in an another machine for my winform application? 我应该使用哪种方法将数据库或目录服务(AD LDS(ldap))用于Windows应用程序(.net)的角色管理?为什么? - Which approach should i use database or directory services (AD LDS(ldap)) for role management a windows application (.net)?And Why? 在这种情况下我应该使用例外吗? - Should I use an exception in this case? 我应该使用哪种桌面应用程序架构模式? - Which architecture pattern for a desktop application should i use? 我应该为图表使用哪种Web应用程序技术? - Which web application technology should I use for graphs? 我应该使用哪个.NET异常来发出外部应用程序故障信号? - Which .NET exception should I use for signaling external application failure? 我应该为Windows应用程序使用哪个事件处理程序? - Which Event handler should i use for my windows application?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM