为银行交易生成 OrderId 的最佳方法是什么?
我需要生成一个不带任何前导零的 9 位订单 ID。最好的方法是什么?
我的想法是:创建一个具有唯一 ID 列的表,然后在 C# 代码中生成一个 100000000 到 999999999 之间的随机数,并尝试将其插入到表中,直到成功。在此获得唯一约束异常并重新生成数字的机会有多大?
如果我的思考方向正确,有什么方法可以在 sql server 本身中执行此操作,而不是在 C# 代码中处理异常然后重新生成?
或者还有其他最好的方法来做到这一点吗?
谢谢
I need to generate a 9 digit order id without any leading zeroes. What is the best way to do this ?
What I think of is: Create a Table with a unique ID Column and then generate a random number between 100000000 and 999999999 in C# Code and try to insert it into the table until I am successful. What are the chances of getting Unique Constraint Exception in this and re-generating the number ?
If I am thinking in the right direction, is there any way to do this in the sql server itself rather than handling exception in the C# code and then re-generating ?
Or is there any other best method to do this ?
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
出色地。如果与所有可能性相比,您的交易数量保持相对较低,它甚至可能会起作用,但这似乎是错误的。捕获异常并重试?
您是否有任何理由不使用自动增量键(从 100000000 开始并不断计数)?
Well. It would probably even work if number of your transactions would remain relatively low compared to all the possibilities, but that seems really wrong. Catching exceptions and retrying?
Do you have any reasons not to use autoincrement key, starting with 100000000 and counting?
您可以使用 SQL Server 中的身份种子功能并定义起始值 http://msdn.microsoft.com/en-us/library/aa933196(v=sql.80).aspx
You can use identity seed feature in SQL Server and define the starting value http://msdn.microsoft.com/en-us/library/aa933196(v=sql.80).aspx
如果您的目标是生成看似随机、唯一的交易 ID,我建议使用交易所有者 (userid) 的部分和交易本身的部分,并将它们组合起来生成您的唯一交易 ID。如果这不可能,那么我建议将 GUID 转换为十进制。操作方法如下:
将 System.Decimal 转换为 System.Guid
If your goal is to generate a seemingly random, unique transaction ID, I suggest using parts from the transaction owner (userid) and parts from the transaction itself and combine those to generate your unique transactionid. If that's not possible, then I suggest converting a GUID to a decimal. Here's how to do it:
Converting System.Decimal to System.Guid
如果您有充分的理由希望 ID 按随机顺序排列,也许您可以用 C# 编写一个一次性实用程序来生成随机数字列表并将它们插入到 SQL 表中。然后,当您的程序需要 ID 时,它可以从该表中选择下一个可用的 ID。当然,您需要一个位字段或其他内容来标记哪些 ID 已被使用。您可能希望将选择和标记操作放入存储过程中,并让该过程在工作时锁定表,以便并发进程在有机会将其标记为已使用之前不会获得相同的 ID。
If you have a compelling reason for wanting the IDs to be in random order, maybe you could write a one-time utility program in C# to generate the random list of numbers and insert them into a SQL table. Then, when your program needs an ID, it can select the next available one from that table. Of course, you'd need a bit field or something to mark which IDs have been used. You might want to put the select and mark operations into a stored procedure and have the procedure lock the table while it's working so simultaneous processes don't get the same ID before they've had a chance to mark it as used.