我有一张表格中有 int字段。该字段应填充随机数,并且应该是唯一的。什么是最好的解决方案?我应该生成一个随机数并检查它是否存在于表中?顺便说一句,我正在使用ASP.NET和C#开发一个Web应用程序。
答案 0 :(得分:2)
你真的需要它是随机的吗?如果您只需要一个唯一的整数值,请使用Identity。查看this link
编辑: 对于随机数(BigInt),您可以尝试:
SELECT ABS(CAST(CAST(NEWID() AS VARBINARY(5)) AS Bigint)) as UniqueNo
在here
中找到它答案 1 :(得分: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);
}
答案 2 :(得分:0)
使用Front End
来自C#
Guid.NewGuid().ToString("N") //Replaces all - will Empty values.
Final value will be numeric
来自数据库
newid()
这两种技术都会给你独特的结果。
答案 3 :(得分:0)
尝试http://msdn.microsoft.com/en-us/library/system.random.aspx生成随机数,然后查询数据库以检查该值是否存在。您应该能够通过选择'int field'='random number'的行并检查@@ rowcount = 0来确定它。