How to resolve "Violation of PRIMARY KEY constraint" after a DB reset - sql-server

Use Case:
I am performing performance execution on an database and I am trying to do following:
I took an backup of the database (the mdf and ldf file) at the early stage (lets called a "baselinecopy").
After that I execute some performance script .And the database reach to baselinecopy+Additional_Row (let it be "NewDatabase") from the test.
Then I replace the database baselinecopy with NewDatabase & start the server. While trying to perform operation on application it is giving me Violation of PRIMARY KEY constraint to test_order. Cannot insert duplicate key in object.
I check the "IDENTITY" but the table has no identity set.
Any thoughts on this ?

Violation of PRIMARY KEY constraint to test_order. Cannot insert duplicate key in object.
This is exactly what it says.
You have defined a primary key on a table and are attempting to insert a record that contains the same primary key as an existing record.
It does not need to be an identity column to be a primary key column.

Related

Why is Entity Framework ignoring existing GUIDs on insert?

I have a table defined in Sql Server with a GUID primary key and a default of newsequentialid():
CREATE TABLE [dbo].[mything](
[id] [uniqueidentifier] NOT NULL,
[foo] [varchar][32] NULL,
CONSTRAINT [PK_mything] PRIMARY KEY CLUSTERED
(
[id] ASC
)
)
GO
ALTER TABLE [dbo].[mything]
ADD CONSTRAINT [DF_mything_id]
DEFAULT (newsequentialid()) FOR [id]
GO
And when I add an entity with the guid primary key already set, it ends up as a record in the database with a new guid primary key.
var anEntity = new mything
{
id = "17870C25-FC04-EB11-80E9-000C29F38B54",
foo = "Some stuff",
}
dbContext.mythings.Add(anEntity);
dbContext.SaveChanges();
EF seems to ignore the guid that was provided in the record and writes the record with a new Guid.
What I would expect is that the record provided had a null guid, it would be populated with a new guid, and if it was not null it would be used unchanged. But that's not what I'm seeing happen.
I'm seeing duplicate records, with different GUIDs, instead of primary key violation exceptions, because the GUIDs I'm providing in my EF entities are being ignored.
Why could this be happening?
Please tell me this isn't by design!
===
OK, this does seem to be by design.
First, this isn't in SQL server. If I try to insert a record with the id field set, it inserts, or fails with a primary key failure if there is already a record with that id. It only creates a new GUID for the id field if the provided id field is null.
But in EF, the value in the id field is ignored, and a new GUID is generated every time.
It was suggested to me that EF was behaving this way so as to follow the same pattern as when using autoincrement keys. And that does seem to be the case.
In SQL Server, if you try to provide a value to an autoincrement key field on an insert, you get an error:
Cannot insert explicit value for identity column in table
But in EF, the value you provide is ignored, and a new value is generated.
So in this respect, Entity Framework is consistent. Consistently wrong, but consistent.
First step I'd look at to narrow this down is to capture a Profiler/Extended Event trace at the database to see exactly what EF is sending to the database.
Your expectation of the database behaviour is correct - so I'd want to understand where it is breaking down first

SSDT Adding 2 columns to the end of a table leads to table rebuild

We are using Azure DevOps to automatically deploy changes to our production database, which is an Azure SQL database. This runs fine for most releases, as we do limited changes most of the time. What does give us problems sometimes, is table rebuilds which take a lot of time to complete. The end result is fine, only the long running time leads to website downtime which we can ill afford.
We are using a database project in Visual Studio to manage this and some other databases. This includes a xml file which we include in publishing with SSDT which contains the settings of the deployment process. (Ie ignore column order and the likes).
The following change leads to a table rebuild of the table:
CREATE TABLE [dbo].[AccountCompany] (
[CompanyId] INT IDENTITY (1, 1) NOT NULL,
[AccountTypeCode] NVARCHAR (2) DEFAULT ('00') NOT NULL,
<Various columns, some with defaults>
[PONumberMandatoryUpstream] BIT NULL,
[PONumberMandatoryDownstream] BIT NULL,
CONSTRAINT [PK_AccountCompany] PRIMARY KEY CLUSTERED ([CompanyId] ASC),
CONSTRAINT [FK_AccountCompany_AccountBranchType] FOREIGN KEY ([BranchTypeCode]) REFERENCES [dbo].[AccountBranchType] ([BranchTypeCode]),
CONSTRAINT [FK_AccountCompany_AccountCustomerBusinessSegment] FOREIGN KEY ([BusinessSegment]) REFERENCES [dbo].[AccountCustomerBusinessSegment] ([BusinessSegmentCode]),
CONSTRAINT [FK_AccountCompany_AccountDmsEndpoint] FOREIGN KEY ([DmsEndpointId]) REFERENCES [dbo].[AccountDmsEndpoint] ([DmsEndpointId]),
CONSTRAINT [FK_AccountCompany_AccountDmsType] FOREIGN KEY ([DmsTypeCode]) REFERENCES [dbo].[AccountDmsType] ([DmsTypeCode]),
CONSTRAINT [FK_AccountCompany_AccountType] FOREIGN KEY ([AccountTypeCode]) REFERENCES [dbo].[AccountType] ([AccountTypeCode]),
CONSTRAINT [FK_AccountCompany_Currency_Purchase] FOREIGN KEY ([PurchaseCurrencyCode]) REFERENCES [dbo].[Currency] ([CurrencyCode]),
CONSTRAINT [FK_AccountCompany_Currency_Sales] FOREIGN KEY ([SalesCurrencyCode]) REFERENCES [dbo].[Currency] ([CurrencyCode]),
CONSTRAINT [FK_AccountCompany_MasterLanguage] FOREIGN KEY ([CultureCode]) REFERENCES [dbo].[MasterLanguage] ([CultureCode])
);
GO
CREATE NONCLUSTERED INDEX [IX_AccountCompany_LocationCode_Active]
ON [dbo].[AccountCompany]([LocationCode] ASC, [Active] ASC)
INCLUDE([AccountTypeCode], [BranchTypeCode], [DeliveryTimeDealer], [DeliveryTimeDealerGroup], [DeliveryTimeDealerPreferred], [DeliveryTimeFacingPdc], [DeliveryTimeTotalPaccar], [DmsDealerId], [DmsEndpointId], [DmsTypeCode], [FleetCustomerCode], [Guid], [CultureCode], [LogoAssetSequential], [LogoUrl], [Name], [PurchaseCurrencyCode], [RowVersion], [RushOrder], [SalesCurrencyCode]);
GO
CREATE NONCLUSTERED INDEX [IX_AccountCompany_Guid]
ON [dbo].[AccountCompany]([Guid] ASC);
GO
CREATE NONCLUSTERED INDEX [IX_AccountCompany_DmsTypeCode]
ON [dbo].[AccountCompany]([DmsTypeCode] ASC);
GO
CREATE NONCLUSTERED INDEX [IX_AccountCompany_AccountTypeCode]
ON [dbo].[AccountCompany]([AccountTypeCode] ASC);
The last 2 columns, PONumberMandatoryUpstream and PONumberMandatoryDownstream, probably lead to a table rebuild. Both columns are new and are added to the end of the table, with no foreign keys/constraints/indexes. If I manually do a comparison with the schema compare, I see just an ALTER TABLE ADD COLUMN statement which does not rebuild the table.
For some reason the automatic deployment decides the table needs rebuilding.
Anyone with an idea why SSDT thinks the table needs to be rebuild?
My first guess it might have something to do with the settings in the publish xml file. I tried comparing these settings with the ones in the schema compare, but there seem to be no differences.
If needed I can include the deployment log and publish settings file.
I figured out what the issue was after 2 days of debugging. Turns out one of our admins enabled database discovery and classification https://learn.microsoft.com/en-us/azure/sql-database/sql-database-data-discovery-and-classification?tabs=azure-t-sql. This adds some extra SQL statements regarding specific columns and classification in the table definition, which were not in the database project. Every deployment these tables were rebuild, which in our case were 44 tables.
This classification structure is pretty new and ssdt deployment can't yet handle this in a pipeline. Adding these statements to the database project didn't work, as that then gave errors in the pipeline like unknown statement. Our only option was to disable classification until this is supported by ssdt.

Primary key no defined access database

I am developping an application in wpf. I have to work with an existing database in Access.
I used the ORM EntityFramework.
My problem is : in the database, its exists a table with no primary key so I can't add any values in this table.
The Error I get is: no primary key defined. I can change the definition of the table.
How can I solve my problem ? thx
So as to createy a primary key before you begin you must know that
a table can contain only one PRIMARY KEY constraint.
All columns defined within a PRIMARY KEY constraint must be defined as NOT NULL. If nullability is not specified, all columns participating in a PRIMARY KEY constraint have their nullability set to NOT NULL.
Security
Permissions
Creating a new table with a primary key requires CREATE TABLE permission in the database and ALTER permission on the schema in which the table is being created.
Creating a primary key in an existing table requires ALTER permission on the table.

SQL Server merge replication causes foreign key failures

In my application, using SQL Server 2005, I'm having two tables, let's call them Table A and Table B; a foreign key constraint is defined on Table B, referencing the primary-key column in Table A, which is an auto-generated integer ID. I'm running the following simple transaction:
Start transaction
Insert a row to table A
Retrieve the last-generated ID ("SELECT ##IDENTITY ... ")
Insert data to table B, using this ID
Commit
It all works well, until I'm trying to create merge replication (continuous) with another SQL Server 2005. Both publisher and subscriber now fail this transaction when trying to insert data to table B, because of foreign key constraint failure:
The INSERT statement conflicted with the FOREIGN KEY constraint "FK_TableB_TableA". The conflict occurred in database "MyDB", table "TableA", column 'ID'.
I was not able to make it work by committing after inserting data to table A. However, after removing the merge replication, everything worked. The database code is written in C++, using ADO.
Is the replication interfering with the transaction anyhow? Any other possible explanation?
Are the Primary Key values on Table A at both server nodes discrete from one another (In other words are you using Identity Range management at each node)?
Also, has the Foreign Key constraint been configured with the Not For Replication property?
I would assume that because your Foreign Key constraint has already been enforced locally at the Publisher, that you do not need to re-check it when merging with the Subscriber.
Looks like the issue is related to the scope of the ##IDENTITY function. When I used LAST_IDENT('TableB') instead, things seem to work.
As described in MSDN:
IDENT_CURRENT returns the last identity value generated for a specific table in any session and any scope.
##IDENTITY returns the last identity value generated for any table in the current session, across all scopes.
SCOPE_IDENTITY returns the last identity value generated for any table in the current session and the current scope.

Adding a foreign key constraint fill up my transaction log

When trying to add a foreign key constraint on an existing table in SQL Server 2000, I get an error message saying that the transaction log is full. What are the possible reasons why data is being added to the transaction log when a foreign key constraint is being created and what remedy can I apply to each of these reasons? Also, if multiple reasons exist, how can I diagnose which of those reasons are relevant to me?
The script causing the error is a simple one that follows this pattern:
ALTER TABLE [dbo].[tableName] ADD
CONSTRAINT [key_name] FOREIGN KEY
(
[columnId]
) REFERENCES [dbo].[otherTableName] (
columnId
)
GO
It turns out that the log was being filled from a previous statement - one that modifies a column on a large table. Adding the foreign key constraint was just the straw that broke the camel's back.

Resources