由弃用自增ID列之我的看待
看过园子里“Repository”两弃自增ID的文章以及众园友的评论,对是用还是不用和主键类型的设定(INT vs GUID vs CHAR …)陷入了胶着状态。
不用自增ID(INT)认为:
1.数据迁移合并有冲突问题。
2.表列之间有依赖关系,后者不便取相应值。
针对此出了不少解决方案,A、B、C、D ……,本人对任何解决方案的看法是:适当的方案就好。如就医看病总会有副作用一样。
借着这些问题,重新补习了下相关知识(仅限MSSQL),写出本人一点简要看法。不足之处请多指教。
在用自增下:
1.新值,开关控制启用否 SET IDENTITY_INSERT [ database. [ owner. ] ] { table } { ON | OFF }
2.同值,重建表或列或GUID列。
3.依赖,IDENT_CURRENT(‘tablename’)+种子增量(不知这算不算预知了)。
在用GUID主键下:
对这个存疑,广泛是在性能上的影响,毕竟其长度长了不少。
在我现有的能力理解下,主键或许不应该人为的加上意义。即只给机器懂,人要看懂自编码为列。也就说用什么类型为主键会无关了。
另GUID的产生有NewID()、NewSequentialID()、自定义。NewSequentialID()做默认值会更好。
附上取自增ID方法的各自差异
SELECT @@IDENTITY It returns the last IDENTITY value produced on a connection, regardless of the table that produced the value, and regardless of the scope of the statement that produced the value. @@IDENTITY will return the last identity value entered into a table in your current session. While @@IDENTITY is limited to the current session, it is not limited to the current scope. If you have a trigger on a table that causes an identity to be created in another table, you will get the identity that was created last, even if it was the trigger that created it.
(大意为:在当前连接会话下,只管返回最后自增ID,而不管从哪个表。假如插入A表时,A表有插入触发器从而触发B表进而B有自增ID就会取到它了。)
SELECT SCOPE_IDENTITY() It returns the last IDENTITY value produced on a connection and by a statement in the same scope, regardless of the table that produced the value. SCOPE_IDENTITY(), like @@IDENTITY, will return the last identity value created in the current session, but it will also limit it to your current scope as well. In other words, it will return the last identity value that you explicitly created, rather than any identity that was created by a trigger or a user defined function. (大意为:在当前连接会话下,只管返回当前本身表自增ID,而不管他表。假如插入A表时,A表有插入触发器从而触发B表进而B有自增ID也不会取到它了。)
SELECT IDENT_CURRENT(‘tablename’) It returns the last IDENTITY value produced in a table, regardless of the connection that created the value, and regardless of the scope of the statement that produced the value. IDENT_CURRENT is not limited by scope and session; it is limited to a specified table. IDENT_CURRENT returns the identity value generated for a specific table in any session and any scope. (大意为:不管在什么情况下,只管返回指定表自增ID。)