I've got a batch of rows that need to be inserted within a single transaction, the first row is a header and all subsequent rows must reference the first.
This is how I'm attempting to insert the first row:
using ( var connection = new SqlConnection( _connectionString ) )
{
connection.Open();
var transaction = connection.BeginTransaction();
try
{
// create the record header
using ( var createRecordCommand = connection.CreateCommand() )
{
createRecordCommand.CommandText =
"DECLARE @RecordId INT;" +
$"INSERT INTO ..." +
"SET @RecordId = scope_identity();";
createRecordCommand.Transaction = transaction;
createRecordCommand.ExecuteNonQuery();
I'm struggling to reference RecordId in subsequent statements, it seems to think the variable @RecordId is not declared in the snippet below. 'Must declare the scalar variable "@RecordId".'
using ( var createAttributeCommand = connection.CreateCommand() )
{
createAttributeCommand.Transaction = transaction;
createAttributeCommand.CommandText =
$"INSERT INTO ... (RecordId,...) VALUES (@RecordId,...)";
Also extracting the @RecordId variable as a parameter is proving difficult, it doesn't like it when I use the below line in conjunction with DECLARE @RecordId INT;
createRecordCommand.Parameters.Add( new SqlParameter( "@RecordId", SqlDbType.Int ) { Direction = ParameterDirection.Output } );