I'm using tables in Access (2013), that are linked to an SQL database. The primary key is a column 'RowId', containing a GUID.
When I'm adding a new record to the table, and I leave the RowId blank. The record is inserted in the SQL database, but then the added record is filled up with data of another record.
After investigating the problem with SQL Server Profiler, I discovered that this happens:
First, an INSERT statement is processed:
exec sp_executesql
N'INSERT INTO "{table}" ("{column1}","{column2}", {column4}")
VALUES (@P1,@P2,@P3)',
N'@P1 int,@P2 nvarchar(50),@P3 nvarchar(50)',
3438,
N'Smith',
N'Sofia'
But then, a second statement is passed, in order to get the values of the saved record (I guess):
declare @p1 int
set @p1=5
exec sp_prepexec
@p1 output,
NULL,
N'SELECT "{column1}","{column2}", {column3}","{column4}","{column5}", {column6}",
"RowID","RV" FROM "{table}" WHERE "RowID" IS NULL'
select @p1
The RowID is not initially given when creating the record, so now Access asks for an row with RowId IS NULL. This happens twice, and fails twice. Then, the RowId is asked by the parameters that are given in the insert statement:
exec sp_executesql
N'SELECT "{table}"."RowID"
FROM "{table}"
WHERE "{column1}" = @P1 AND "{column2}" = @P2 AND "{column4}" = @P3',
N'@P1 int,@P2 nvarchar(50),@P3 nvarchar(50)',
3438,
N'Smith',
N'Sofia'
If there is another record with the same parameters (eg 3438, Smith, Sofia) exists, the RowID of this record given back, and the new record in Access is filled in with data from this other record (including the wrong RowID). Every action on this record is made on the wrong record now, as the wrong RowID is given with the statements. After I refresh the table, the newly inserted record is shown, with the right data and new generated RowID.
How can I prevent this from happening? How can I make it so the right data is shown immediately after I insert the row?