首页 > 解决方案 > 如何在 MS SQL 中插入标识列

问题描述

我有以下代码:

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

该表computers包含一个INT idientity(1,1)名为 的列id

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

标签: c#sqlsql-servertsql

解决方案


对于自动递增的标识列,数据库处理 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();
        }
    }
}

推荐阅读