简体   繁体   English

如何用自动增量主键在表中插入空行?

[英]How do I insert an empty row in a table with an auto-Increment primary key?

I just want to grab the primary using the SqlTransaction method. 我只想使用SqlTransaction方法获取主要对象。

This is what I have so far: 这是我到目前为止的内容:

using (SqlTransaction transaction = connection.BeginTransaction())
{
    // insert IT Requirements
    string strITStaff = "INSERT INTO ITReq";
    strITStaff += "SELECT SCOPE_IDENTITY()";

    SqlCommand cmdITStaff = new SqlCommand(strITStaff, connection, transaction);
    ddlITSupport.SelectedValue.ToString());

    int ITStaffReq = Convert.ToInt32(cmdITStaff.ExecuteScalar());

    // update lanGaymen
    string strUpdatePhaseSix = "UPDATE lanGaymen SET ";
    strUpdatePhaseSix += "itReqID = @updateITReq ";
    strUpdatePhaseSix += "WHERE seasonID = @compareSeason";

    SqlCommand cmdUpdatePhaseSix = new SqlCommand(strUpdatePhaseSix, connection, transaction);
    cmdUpdatePhaseSix.Parameters.AddWithValue("@updateITReq", ITStaffReq);
}

In order to insert the default values including the "auto-increment" value, you need to use DEFAULT VALUES in your INSERT . 为了插入包括“自动增量”值在内的默认值,您需要在INSERT使用DEFAULT VALUES Also, you need to have at least a ; 另外,您至少需要有一个; between your INSERT and your SELECT SCOPE_IDENTITY() (your current code doesn't have a space nor a semicolon between the two statements): 在您的INSERTSELECT SCOPE_IDENTITY() (您的当前代码在两个语句之间没有空格或分号):

string strITStaff = "INSERT INTO ITReq DEFAULT VALUES;  SELECT SCOPE_IDENTITY()";

This will insert all default values into the ITReq table, and then select the newly inserted IDENTITY from that table. 这会将所有默认值插入ITReq表,然后从该表中选择新插入的IDENTITY

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何自动增加表格中的列? - How do I auto-increment a column in my table? 如何重新分配自动增量主键值? - How can I re-assign an auto-increment primary key value? 如何使用带有ASP.Net/C#的MySQL ODBC将自动增量ID插入MySQL表? - How do I insert the auto-increment ID into a MySQL table using MySQL ODBC with ASP.Net/C#? 在Linq-to-SQL插入期间,何时可以使用自动增量主键值? - During Linq-to-SQL insert, when does an auto-increment primary key value become available? Linq to SQL插入主键,因为tinyint设置为自动递增,会显示错误消息 - Linq to SQL insert with primary key as tinyint set to auto-increment gives error message 我能否在拥有其他键的同时获得实体框架中自动增量的主键 - Can I get a primary key to auto-increment in Entity Framework, while having other key 如何将由自动递增创建的一个表中的主键作为外键插入第二个表中? - How to insert primary key from one table which created by auto increment, into a second table as forign key? 如何设置新行中的列值,使其具有与表的自动增量主键相同的值? - What can I do to set the value of a column in a new row in such a way that it have the same value of the auto increment primary key of the table? 如何自动增加词典的键? - How to auto-increment a key of a Dictionary? 使用Entity Framework Core在部分主键上自动递增 - Auto-increment on partial primary key with Entity Framework Core
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM