Create Table DDL causes sql server to hang - sql

Is there anything in this DDL statement that could cause the system to hang and create long running query?
-- Abort on any error
SET XACT_ABORT ON
GO
-- FUll isolation
SET TRANSACTION ISOLATION LEVEL SERIALIZABLE
GO
BEGIN TRANSACTION
GO
CREATE TABLE ClientPayerCrosswalkMapping
(
id INT IDENTITY(1, 1) NOT NULL,
lbxid INT NOT NULL,
ClientPayerID NVARCHAR(80),
CONSTRAINT PK_ClientPayerCrosswalkMapping_ID PRIMARY KEY CLUSTERED (id),
CONSTRAINT UN_lbxid UNIQUE(lbxid),
CONSTRAINT FK_LockboxDocumentTracking FOREIGN KEY (lbxid)
REFERENCES LockboxDocumentTracking(lbxid)
);
GO
This is on SQL Server 2005, at that time system was under moderate load.
This is new table so why would the system hang, my only suspicion is that the table have a CONSTRAINT

Try this without creating any transaction:
CREATE TABLE ClientPayerCrosswalkMapping
(
id INT IDENTITY(1, 1) NOT NULL,
lbxid INT NOT NULL,
ClientPayerID NVARCHAR(80),
CONSTRAINT PK_ClientPayerCrosswalkMapping_ID PRIMARY KEY CLUSTERED (id),
CONSTRAINT UN_lbxid UNIQUE(lbxid),
CONSTRAINT FK_LockboxDocumentTracking FOREIGN KEY (lbxid)
REFERENCES LockboxDocumentTracking(lbxid)
);

Related

SQL Server deployment using DACPAC resulted into creating table without Foreign Keys

I am facing a strange issue,
I have the following SQL table definition,
CREATE TABLE [dbo].[ParameterValue]
(
[ParameterValueID] INT NOT NULL IDENTITY(1, 1),
[ParameterID] INT NULL,
[FieldDefinitionID] INT NULL,
[ParameterValue] VARCHAR(2000) NULL,
[ParameterValueTypeID] SMALLINT NOT NULL DEFAULT 0,
)
GO
-- Constraints and Indexes
ALTER TABLE [dbo].[ParameterValue] ADD CONSTRAINT [Pk_ParameterValue_ParameterValueID] PRIMARY KEY CLUSTERED ([ParameterValueID])
GO
ALTER TABLE [dbo].[ParameterValue] ADD CONSTRAINT [FK_ParameterValue_Parameter] FOREIGN KEY ([ParameterID]) REFERENCES [Parameter]([ParameterID])
GO
ALTER TABLE [dbo].[ParameterValue] ADD CONSTRAINT [FK_ParameterValue_FieldDefinition] FOREIGN KEY ([FieldDefinitionID]) REFERENCES [FieldDefinition]([FieldDefinitionID])
GO
I noticed that in the table creation script, only the Primary key constraint is added; foreign key constraints are missing completely.
So the resultant table is created without the foreign keys.
What is the cause behind this?
Note: SQL Server Version --> 13.0.5103.6

SQL The INSERT statement conflicted with the FOREIGN KEY constraint "FK_Score_Gebruikersnaam"

I have a create script for my SQL database (see below). Everything works fine except when I run the INSERT INTO Scores() I get an error.
The error I get is:
The INSERT statement conflicted with the FOREIGN KEY constraint "FK_Score_Gebruikersnaam". The conflict occurred in database "gamescores", table "dbo.Players", column 'gebruikersnaam'
I don't understand what I'm doing wrong so please help me :)
I already tried to drop the database first and then run the rest of the script but that didn't help. I think something went wrong with the foreign key...
Thanks!
USE master;
GO
DROP DATABASE IF EXISTS [gamescores];
CREATE DATABASE gamescores;
GO
USE gamescores;
GO
SET DATEFORMAT dmy;
CREATE TABLE [Players]
(
[gebruikersnaam] VARCHAR(75) NOT NULL,
[voornaam] VARCHAR(75) NOT NULL,
[achternaam] VARCHAR(75) NOT NULL,
[emailadres] VARCHAR(75) NOT NULL,
[geboortdatum] DATE NOT NULL
);
CREATE TABLE [Scores]
(
[scoreID] INT IDENTITY(1,1) NOT NULL,
[gebruikersnaam] VARCHAR(75) NOT NULL,
[aantalScore] INT NOT NULL,
[datum] DATE NOT NULL
);
ALTER TABLE [Players]
ADD CONSTRAINT [PK_Speler]
PRIMARY KEY (gebruikersnaam);
ALTER TABLE [Scores]
ADD CONSTRAINT [PK_Score]
PRIMARY KEY (scoreID);
ALTER TABLE [Players]
ADD CONSTRAINT [AK_Speler_Emailadres]
UNIQUE (emailadres)
ALTER TABLE [Scores]
ADD CONSTRAINT [FK_Score_Gebruikersnaam]
FOREIGN KEY (gebruikersnaam) REFERENCES Players(gebruikersnaam);
GO
INSERT INTO Players([gebruikersnaam], [voornaam], [achternaam], [emailadres], [geboortdatum])
VALUES ('apraundlin1', 'Angelle', 'Praundlin', 'apraundlin1#mapy.cz', '15-9-1997'),
('rnoore3', 'Rebekah', 'Noore', 'rnoore3#vk.com', '9-10-1987'),
('nplevinh', 'Nicolais', 'Plevin', 'nplevinh#mediafire.com', '18-3-2001');
-- SCORE table vullen
INSERT INTO Scores([gebruikersnaam], [aantalScore], [datum])
VALUES ('rsprasen0', 551, '15-5-2021'),
('fwhawell8', 309, '8-4-2021'),
('rgravett9', 1063, '16-11-2021');
You got an error because the database schema, though a foreign key, enforces that a player referenced in the scores table must first exist in the players table. Add the player to the players table, before trying to update their score in the scores table.

Speed up SQL Server AFTER INSERTED trigger

I have a SQL Express 2019 server with a table on which I created a trigger that updates a row of that table when another row is inserted. I have to INSERT about 100,000 rows a day. Unfortunately the insert takes about 1-2 hours with the trigger, which is okay but frustrating while testing.
This is my table structure:
[ID] BIGINT IDENTITY(1,1) NOT NULL PRIMARY KEY,
[REPORT_ID] BIGINT NOT NULL,
[CLUSTER_ID] BIGINT NOT NULL,
[ID_NEXT] BIGINT NULL,
[CREATED_AT] DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
[ID_SUCCESSOR] BIGINT NULL,
[CREATED_AT] DATETIME NOT NULL DEFAULT GETUTCDATE(),
CONSTRAINT [FK_CRASHREPORTS_REPORTS2CLUSTERS_CRASHREPORTS] FOREIGN KEY ([REPORT_ID]) REFERENCES [CRASHREPORTS]([ID]),
CONSTRAINT [FK_CRASHREPORTS_REPORTS2CLUSTERS_ID_PREV] FOREIGN KEY ([ID_NEXT]) REFERENCES [CRASHREPORTS_REPORTS2CLUSTERS]([ID]),
CONSTRAINT [FK_CRASHREPORTS_REPORTS2CLUSTERS_ID_PREV] FOREIGN KEY ([ID_SUCCESSOR]) REFERENCES [CRASHREPORTS_REPORTS2CLUSTERS]([ID]),
CONSTRAINT [FK_CRASHREPORTS_REPORTS2CLUSTERS_CRASHREPORTS_CLUSTERS_ID] FOREIGN KEY ([CLUSTER_ID]) REFERENCES [CRASHREPORTS_CLUSTERS]([ID])
And this is my trigger:
CREATE TRIGGER [dbo].[update_prev_after_insert]
ON [dbo].[CRASHREPORTS_REPORTS2CLUSTERS]
AFTER INSERT
AS
BEGIN
MERGE INTO [dbo].[CRASHREPORTS_REPORTS2CLUSTERS] T
USING inserted I
ON T.ID != I.ID AND T.ID_SUCCESSOR is NULL and T.REPORT_ID = I.REPORT_ID
WHEN MATCHED THEN
UPDATE SET ID_SUCCESSOR = I.ID;
END
Everything works as expected but really slow. Does anyone knows how to speed this up?

Foreign key in SQL Server - which style to use?

In my database, I have the following code
CREATE TABLE [Users]
(
userID INT NOT NULL IDENTITY(1,1) PRIMARY KEY,
Username VARCHAR(255),
Password VARCHAR(255)
);
CREATE TABLE [Image]
(
ImageID INT NOT NULL IDENTITY(1,1) PRIMARY KEY,
Imagename VARCHAR,
userID INT,
FOREIGN KEY(userID) REFERENCES Users (userID)
);
However, here on stackOverflow and multiple other sites, people suggest writing it like this:
CREATE TABLE [Users]
(
userID INT NOT NULL IDENTITY(1,1) PRIMARY KEY,
Username VARCHAR(255),
Password VARCHAR(255)
);
CREATE TABLE [Image]
(
ImageID INT NOT NULL IDENTITY(1,1) PRIMARY KEY,
Imagename VARCHAR,
userID INT,
CONSTRAINT fk_Users
FOREIGN KEY(userID) REFERENCES Users (userID)
);
I've tried executing both statements, and it seems to do the same..
What am I missing, what's the trick when writing CONSTRAINT fk_Users?
Writing constraint allows you to name the constraint.
In general, you notice this when the constraint is violated. If you have an opportunity to name the constraint, the error message will make more sense.
For instance, this:
The INSERT statement conflicted with the FOREIGN KEY constraint
"fk_image_userId". The conflict occurred in database "rextester",
table "dbo.Users", column 'userID'.
The statement has been terminated.
is clearer than this:
The INSERT statement conflicted with the FOREIGN KEY constraint
"FK__Image__userID__09211CD4". The conflict occurred in database
"rextester", table "dbo.Users", column 'userID'.
The statement has been terminated.
In addition, the constraint name is used in the alter table when you drop or disable the constraint, so having a reasonably named constraint makes that easier.

How can I stop the delete on a parent if a child entity that references that parent exists?

I have the following DDL that I am using with SQL Server 2012:
CREATE TABLE Subject (
[SubjectId] INT IDENTITY (1, 1) NOT NULL,
[Name] NVARCHAR (50) Not NULL,
CONSTRAINT [PK_Subject] PRIMARY KEY CLUSTERED ([SubjectId] ASC)
)
CREATE TABLE Topic (
[TopicId] INT IDENTITY (1, 1) NOT NULL,
[Name] NVARCHAR (50) NOT NULL,
[SubjectId] INT NOT NULL,
CONSTRAINT [PK_Topic] PRIMARY KEY CLUSTERED ([TopicId] ASC)
)
ALTER TABLE [Topic] WITH CHECK ADD CONSTRAINT [FK_TopicSubject]
FOREIGN KEY([SubjectId]) REFERENCES [Subject] ([SubjectId])
ON DELETE CASCADE
CREATE TABLE SubTopic (
[SubTopicId] INT IDENTITY (1, 1) NOT NULL,
[TopicId] INT NOT NULL,
[Name] NVARCHAR (4000) Not NULL,
CONSTRAINT [PK_SubTopic] PRIMARY KEY CLUSTERED ([SubTopicId] ASC)
)
ALTER TABLE [SubTopic] WITH CHECK ADD CONSTRAINT [FK_SubTopicTopic]
FOREIGN KEY([TopicId]) REFERENCES [Topic] ([TopicId])
ON DELETE CASCADE
When I try to run the scripts I get the following message:
{"Introducing FOREIGN KEY constraint 'FK_TopicSubject'
on table 'Topic' may cause cycles or multiple cascade paths.
Specify ON DELETE NO ACTION or ON UPDATE NO ACTION,
or modify other FOREIGN KEY constraints.\r\nCould not create constraint.
See previous errors."}
What I really need is for when a person tries to DELETE a subject when there are topics for the delete to fail. If I include neither DELETE ON CASCADE or DELETE NO ACTION then will this happen. If not then how can I stop the delete on subject happening if there are Topics for that subject?
Short answer is: If you don’t want cascade updates and deletions then use ON DELETE NO ACTION. Same applies for Update.
Here is a copy from MSDN article (it’s SQL Server 2000 but same rules still apply)
ON DELETE NO ACTION
Specifies that if an attempt is made to delete a row with a key referenced by foreign keys in existing rows in other tables, an error is raised and the DELETE is rolled back.
ON UPDATE NO ACTION
Specifies that if an attempt is made to update a key value in a row whose key is referenced by foreign keys in existing rows in other tables, an error is raised and the UPDATE is rolled back.
Please refer to this link. It has given a detail explanation of this error, and also has suggested to create a trigger as an alternative.
Foreign key constraint may cause cycles or multiple cascade paths?