我有一个表,其中有一个int 字段。该字段应填写随机数,并且应该是唯一的。什么是最好的解决方案?我应该生成一个随机数并检查它是否存在于表中?顺便说一句,我正在使用 ASP.NET 和 C# 开发一个 Web 应用程序。
问问题
500 次
4 回答
0
使用 GUID:
public string GetRandomGUID(int length)
{
// Get the GUID
string guidResult = System.Guid.NewGuid().ToString();
// Remove the hyphens
guidResult = guidResult.Replace("-", string.Empty);
// Make sure length is valid
if (length <= 0 || length > guidResult.Length)
throw new ArgumentException("Length must be between 1 and " + guidResult.Length);
// Return the first length bytes
return guidResult.Substring(0, length);
}
于 2012-05-26T10:31:01.047 回答
0
从Front End
使用C#
Guid.NewGuid().ToString("N") //Replaces all - will Empty values.
Final value will be numeric
从数据库
newid()
这两种技术都会给你独特的结果。
于 2012-05-26T11:15:53.350 回答
0
尝试http://msdn.microsoft.com/en-us/library/system.random.aspx生成随机数,然后查询数据库以检查该值是否存在。您应该能够通过选择 'int field' = 'random number' 的行并检查 @@rowcount = 0 来确定它。
于 2012-05-26T11:35:42.417 回答