【问题标题】:autogenerate number from database in c#在c#中从数据库中自动生成数字
【发布时间】:2017-04-22 13:23:12
【问题描述】:

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

代码:

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();
    }
}

【问题讨论】:

  • 我完全不知道你在问什么......
  • 认为我明白你在问什么,有点。如果您试图获得(潜在的)下一个增量值,请使用SELECT IDENT_CURRENT(StudentDetails) + 1 而不是计数。我说潜力是因为在你提交之前它可能会改变。您还需要一个 Identity 列,否则使用 MAX(Id) 如果不是 IDENTITY(应该是)。
  • 或者只使用 Id INT IDENTITY(1,1)
  • 使用排序器
  • 你没有主键?

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


【解决方案1】:

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

例子:

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

这将返回一个唯一编号,即使您删除了一行。

【讨论】:

  • 它给出了无效对象名称'Std_Info.Id'的错误
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-10-23
  • 1970-01-01
  • 1970-01-01
  • 2011-11-10
相关资源
最近更新 更多