2016-12-07 34 views
-3

我使用了下面的解决方案,但是每当我删除特定的行时,它都会重复该数字。从c#中的数据库自动生成数字

代码:

void AutoGenerateId() 
{ 
    SqlConnection cn = new SqlConnection(ConString); 
    string Query = "select COUNT(*) from StudentDetails"; 
    SqlCommand cd = new SqlCommand(Query, cn); 
    try 
    { 
     cn.Open(); 
     int count = Convert.ToInt16(cd.ExecuteScalar()) + 1; 
     txtStudentId.Text = count.ToString(); 
     txtStudentId.Enabled = false; 
    } 
    catch (Exception ex) 
    { 
     lblErrorMsg.Text = ex.ToString(); 
    } 
    finally 
    { 
     cn.Close(); 
    } 
} 
+1

我没有丝毫的线索你在问什么...... – Siyual

+0

我_think_我得到你所问的,有点。如果你想获得(潜在的)下一个增量值,使用'SELECT IDENT_CURRENT(StudentDetails)+ 1'而不是计数。我说潜力是因为它可能会在你犯下之前发生变化。你还需要一个标识列,否则使用MAX(Id)如果不是IDENTITY(它应该是)。 –

+2

或只使用Id INT IDENTITY(1,1) – Steve

回答

3

可以使用sequencer是生成ID并获得下一个。

例子:

string query = "SELECT NEXT VALUE FOR Student.Sequence;" 

这将返回一个唯一的号码,即使你删除行。

+0

它给出错误,无效的对象名称'Std_Info.Id' – WeeZy