简体   繁体   中英

Generating insert statement that includes identity column

I am trying to use CommandBuilder to generate an insert statement that includes an Identity column. For test data generation purposes I want to be able to insert a value into the identity column after Identity Insert has been enabled on the table

var sql = "Select * from Table";
var dataAdapter = new SqlDataAdapter(sql, conn);
dataAdapter.Fill(currentTable);
var cb = new SqlCommandBuilder(dataAdapter);

The command builder does generate the insert statement, but I can't get it to include the identity column. I am creating a generic solution for many tables, so I want to avoid generating the statements manually. Is there a way to trick it to include all columns?

I am also open to other solutions that doesn't include CommandBuilder

commandbuilder uses schema obtained from database, and command building process is not configurable. only option could be something like replace "instert into(" with "insert into(id, " and "values (" with "values (@id, ". dont forget to add @id paramter to the parameter collection too.

Use pure SQL to do this:

set IDENTITY_INSERT dbo.MyTable ON;

insert into dbo.MyTable (id, ...) values (1, ...)
...

set IDENTITY_INSERT dbo.MyTable OFF;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM