C
C#2y ago
Zil

Returning a value after a insert statement

This is the code im running in DotNet:
c++
var testQuery = $@"
INSERT INTO [{databaseName}].[dbo].[steptable] ([Type], [ParentKey], [SubWorkflowCode], [Sequence], [WorkflowKey])
OUTPUT inserted.[Key]
VALUES (@Type, CASE WHEN @ParentKey = 0 THEN NULL ELSE @ParentKey END, @SubWorkflowCode, @Sequence, @WorkflowKey);";

var test = await connection.ExecuteAsync(testQuery, step);
c++
var testQuery = $@"
INSERT INTO [{databaseName}].[dbo].[steptable] ([Type], [ParentKey], [SubWorkflowCode], [Sequence], [WorkflowKey])
OUTPUT inserted.[Key]
VALUES (@Type, CASE WHEN @ParentKey = 0 THEN NULL ELSE @ParentKey END, @SubWorkflowCode, @Sequence, @WorkflowKey);";

var test = await connection.ExecuteAsync(testQuery, step);
After execution the var test contains 1. When i run the same sql statement in mssql the result can be seen in the attached image. I think the 1 comes from the row number, but i need the 441 to be returned into the test variable. Thanks in advance!
5 Replies
Hackmagician
Hackmagician2y ago
isnt that just a row number?
Zil
ZilOP2y ago
yea It is a row number, but i think that is being returned instead of the Key that i want
Anchy
Anchy2y ago
those methods typically return the number of affected rows, not the row number
HimmDawg
HimmDawg2y ago
Sql should have something like select LAST_INSERT_ID() that will get that id for you automatically. Assuming that your connection wasn't terminated and recreated in the meantime
Zil
ZilOP2y ago
I fixed it, didnt see your replies till now, thanks anyway!

Did you find this page helpful?