Cannot insert explicit value for identity column in table 'Department' when IDENTITY_INSERT is set to OFF.
See original GitHub issueIt may be that the connection pool uses different connections. After execution SET identity_insert [Table] ON
, it explicitly inserts the identity column reports an error, even request in the same transaction.
it('mssql -> trans identity_insert on', async () => {
dbConfig.server = dbConfig.host
const pool = await require('mssql').connect(dbConfig)
const trans = pool.transaction()
await trans.begin()
try {
const req = trans.request()
await req.query('SET identity_insert [Items] ON')
const req2 = trans.request()
// id is the identity column
await req2.query("INSERT INTO [Items](Fid, Fname) VALUES(1, 'aName')")
// throw error: Cannot insert explicit value for identity column in table 'Department' when IDENTITY_INSERT is set to OFF.
await trans.commit()
} catch (ex) {
await trans.rollback()
throw ex
}
})
Issue Analytics
- State:
- Created 4 years ago
- Comments:5
Top Results From Across the Web
sql - Cannot insert explicit value for identity column in table ...
The PRIMARY KEY "ID" MUST BE PRESENT from the "INSERT INTO" Statements as long as the ID value does not already exist: If...
Read more >How to Fix the Error 'Cannot insert explicit value for identity ...
Error 1: Set identity_insert OFF ... In the first case, we will insert data into the table with the “IDENTITY INSERT” set to...
Read more >Little SQL Server Tricks: How to Fix “Cannot insert explicit ...
Fore once the error message says exactly what the problem is. In this case, your INSERT statement fails because IDENTITY_INSERT is set to...
Read more >SqlException: Cannot insert explicit value for identity column
This error means you have an identity column in the table, and you're trying to set a value for it. When you have...
Read more >Cannot insert explicit value for identity column in table ...
this is because you are passing some value in a column which is set as identity (auto-increment). hope it helps. otherwise, please send...
Read more >
Top Related Medium Post
No results found
Top Related StackOverflow Question
No results found
Troubleshoot Live Code
Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free
Top Related Reddit Thread
No results found
Top Related Hackernoon Post
No results found
Top Related Tweet
No results found
Top Related Dev.to Post
No results found
Top Related Hashnode Post
No results found
@dhensby I’ve refactored to this, and it works!
You would need to use a transaction. There is no guarantee that the pool will release the same connection both times so each query will be run on different connections.