Oh, sorry. I shortened the SQL to make it readable while I tested and recreated the problem manually in Management Studio.
The full SQL that was run for the SELECT was:
exec sp_executesql N'SELECT [Test].[dbo].[Status].[StatusID] AS [StatusId], [Test].[dbo].[Status].[TransactionID] AS [TransactionId], [Test].[dbo].[Status].[Status], [Test].[dbo].[Status].[Created], [Test].[dbo].[Status].[Description] FROM [Test].[dbo].[Status] WHERE ( ( [Test].[dbo].[Status].[TransactionID] = @TransactionId1))',N'@TransactionId1 int',@TransactionId1=6122482
And then the INSERT:
declare @p3 int
set @p3=NULL
exec sp_executesql N'INSERT INTO [Test].[dbo].[Status] ([TransactionID], [Status]) VALUES (@TransactionId, @Status);SELECT @StatusId=SCOPE_IDENTITY()',N'@StatusId int output,@TransactionId int,@Status tinyint',@StatusId=@p3 output,@TransactionId=6122481,@Status=1
select @p3
Apparently the problem goes away when there's a lot of rows in the Status table, I ran the insert a 1000 times and after that the problem went away.
About your code suggestion: I have no idea
I have only worked on this code base (and with LLBLGen) for a couple of months and the code is several years old with the original developer gone. But you are right, looks like a good rewrite that I will try.
Edit: Yep, with the rewrite the error goes away. Thanks for the help.