【问题标题】:How to insert into an identity column in MS SQL如何在 MS SQL 中插入标识列
【发布时间】:2021-01-24 10:32:35
【问题描述】:

我有以下代码:

SqlCommand writeCommand = new SqlCommand("INSERT INTO computers(id)VALUES()", conn.GetConnection());
            writeCommand.ExecuteNonQuery();

computers 包含一个名为idINT idientity(1,1) 列。

当我运行代码时,我得到一个System.Data.SqlClient.SqlException: Incorrect syntax near ')'。我试图找到解决方案,但在互联网上找不到。

【问题讨论】:

  • 该表还有其他列吗?如果是,他们的价值观应该是什么?如果不是,那么这样的表试图实现什么目的,而 SEQUENCE 之类的东西可能会达到相同的目的并且效果更好。
  • 您的问题是“如何在 MS SQL 中插入标识列”,答案很简单SET IDENTITY_INSERT
  • @Ilyes 我试图让数据库处理 id,但它只是没有。我也尝试过其他语法,但它们也不起作用。

标签: c# sql sql-server tsql


【解决方案1】:

如果该表还有其他列,并且您想用NULL 或其DEFAULT 值填充它们,那么您可以使用DEFAULT VALUES

INSERT INTO dbo.computers
DEFAULT VALUES;

但是,如果您的表只有只有一列,那么亲自使用IDENTITY 是错误的选择;一张只有IDENTITY 的表显然被滥用了。相反,请使用SEQUENCE:

CREATE SEQUENCE dbo.Computers START WITH 1 INCREMENT BY 1;

更好地扩展,并且不会受到您可能遇到的竞争条件的影响。然后,在运行INSERT(或类似的)时,您将使用NEXT VALUE FOR dbo.Computers

【讨论】:

    【解决方案2】:

    对于自动递增的标识列,数据库处理 id 值,除非我错过了您尝试执行的操作。

    public void DemoInsert(string ComputerName, ref int newIdentifier)
    {
        using (var conn = new SqlConnection { ConnectionString = ConnectionString })
        {
            using (var cmd = new SqlCommand { Connection = conn })
            {
                cmd.CommandText = "INSERT INTO computers (ComputerName) " + 
                                  "VALUES (@ComputerName); " + 
                                  "SELECT CAST(scope_identity() AS int);";
    
                cmd.Parameters.AddWithValue("@ComputerName", ComputerName);
    
                cn.Open();
    
                newIdentifier = (int)cmd.ExecuteScalar();
            }
        }
    }
    

    【讨论】:

      【解决方案3】:

      我有类似你的应用程序的代码,想想它是简单的 crud 应用程序

      namespace WindowsFormsApplication1
      {
          public partial class Form1 : Form
          {
              public Form1()
              {
                  InitializeComponent();
              }
      
              SqlConnection con;
              SqlDataAdapter da;
              SqlCommand cmd;
              DataSet ds;
      
              void fillGrid()
              {
                  con = new SqlConnection("Data Source=.;Initial Catalog=schoolDb;Integrated Security=True");
                  da = new SqlDataAdapter("Select * from ogrenciler",con);
                  ds = new DataSet();
                  con.Open();
                  da.Fill(ds, "students");
                  dataGridView1.DataSource = ds.Tables["students"];
                  con.Close();
              }
      
              private void Form1_Load(object sender, EventArgs e)
              {
                  fillGrid();
              }
      
              private void Addbtn_Click(object sender, EventArgs e)
              {
                  cmd = new SqlCommand();
                  con.Open();
                  cmd.Connection = con;
                  cmd.CommandText="insert into students(StudentId,StudentName,StudentSurname,City) values("+StudentId.Text+",'"+StudentName.Text+"','"+StudentSurname.Text+"','"+City.Text+"')";
                  cmd.ExecuteNonQuery();
                  con.Close();
                  fillGrid();        
      
              }
      
              private void Updatebtn_Click(object sender, EventArgs e)
              {
                  cmd = new SqlCommand();
                  con.Open();
                  cmd.Connection = con;
                  cmd.CommandText = "update Students set ogrenci_ad='"+StudentName.Text+"',StudentName='"+StudentSurname.Text+"',City='"+City.Text+"' where StudentId="+StudentId.Text+"";
                  cmd.ExecuteNonQuery();
                  con.Close();
                  fillGrid();
              }
      
              private void Deletebtn_Click(object sender, EventArgs e)
              {
                  cmd = new SqlCommand();
                  con.Open();
                  cmd.Connection = con;
                  cmd.CommandText = "delete from ogrenciler where ogrenci_no="+StudentId.Text+"";
                  cmd.ExecuteNonQuery();
                  con.Close();
                  fillGrid();
              }
          }
      }
      

      【讨论】:

      • 1.) 这似乎没有回答 OP 的问题; 2.) 请修正你代码前面部分的格式; 3.)您的代码在您将 sql 语句与用户输入连接的部分打开您的应用程序以进行 sql 注入攻击。
      猜你喜欢
      • 2021-08-03
      • 1970-01-01
      • 1970-01-01
      • 2013-06-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-07-08
      相关资源
      最近更新 更多