c#中自动生成数据库中的数字

时间:2016-12-07 14:35:56

标签: c# asp.net .net sql-server auto-generate

我使用了下面的解决方案,但每当我删除某一特定行时,它都会复制该数字。

代码:

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 个答案:

答案 0 :(得分:3)

您可以使用sequencer生成ID并获取下一个ID。

示例:

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

即使您删除了一行,也会返回一个唯一的数字。