SQL Server Capture all queries running within a timeframe

esbemjvw  于 2023-10-15  发布在  其他
关注(0)|答案(1)|浏览(103)

My application is inserting duplicate records and I'm trying to figure out what causes that. It could be coming from the UI application, some stored proc or a nightly SQL job. I have looked into everything I can find and can't figure it out.

The table in question can have multiple userId but only one record can be active=1 for a user. So everytime I insert into the table, I update the current record with active=1 to 0 before inserting a new record with active=1.

How can I check where the duplicate values with multiple records of active=1 is happening for a userId?

mm5n2pyu

mm5n2pyu1#

The table in question can have multiple userId but only one record can be active=1 for a user

So put a unique index on userid filtered to active=1,eg

use tempdb

drop table if exists foo

create table foo(userid int, active int)

create unique index ak_only_one_active_row_per_userid on foo(userid) where active = 1
go
insert into foo(userid, active) values (1,1)
insert into foo(userid, active) values (1,1)

The second insert fails with

Msg 2601, Level 14, State 1, Line 10
Cannot insert duplicate key row in object 'dbo.foo' with unique index 'ak_only_one_active_row_per_userid'. The duplicate key value is (1).
The statement has been terminated.

Then you'll both prevent the duplicates from occurring and know who is attempting to insert duplicates because they'll get errors.

相关问题