SQL Check Constraint for Multiple Columns - sql

I am new to the SQL CHECK CONSTRAINT and need something to verify that a combination of three columns in my table does not match those on another row.
I have a Report table including three columns that I need to check against: NAME, CREATEDBY, and TYPE. No multiples of a row with those three values being identical may be created.
Please help!
CREATE TABLE Report(
ReportID INT IDENTITY(1,1) NOT NULL,
[Name] VARCHAR(255) NOT NULL,
CreatedBy VARCHAR(50) NOT NULL,
[Type] VARCHAR(50) NOT NULL,
PageSize INT NOT NULL DEFAULT 25,
Criteria XML NOT NULL
CONSTRAINT CHK_Name_CreatedBy_Type CHECK ([Name], CreatedBy, [Type])
)
ALTER TABLE Report
ADD CONSTRAINT PK_Report PRIMARY KEY (ReportID)
Obviously, the constraint currently makes no sense as it does not provide a boolean...
CONSTRAINT CHK_Name_CreatedBy_Type CHECK ([Name], CreatedBy, [Type])
Thanks in advance!!

You need a UNIQUE constraint:
CONSTRAINT UNQ_Name_CreatedBy_Type UNIQUE ([Name], CreatedBy, [Type])

Related

How to set ID value from another table

Let's say I have these tables:
CREATE TABLE [dbo].[Users]
(
[User_ID] [int] IDENTITY(1,1)PRIMARY KEY NOT NULL ,
[LogIn] [varchar](100) NULL,
[Pass] [varchar](100) NOT NULL,
)
CREATE TABLE [dbo].[Consecutives]
(
[Consecutives_ID] [int] IDENTITY(1,1) PRIMARY KEY NOT NULL,
[Name] [varchar](100) NULL,
[Value] [int] NOT NULL,
)
I'm being asked to be able to set an edit the User_ID that is going to be used next when adding a new user using the value stated on the Consecutive table.
So if for example the Consecutive value is 50, even if the last user added has the User_ID set to 8 the new user's ID will be 50 and the consecutive updated to 51.
I would do it using a foreign key, but obviously I can't set a primary key to be a foreign key.
I can't find a way to do this.
Can someone help me out?
What you are describing is called a one-to-one relationship.
You create such a relationship by connecting both tables with a foreign key referencing their primary keys (or a unique index).
However, since this is a one-to-one relationship, only the main table actually needs the identity specification on it's primary key.
Your requirement to insert a record to the Users based on an existing record in the Consecutives table seems strange to me. Usually, when you have a one-to-one relationship you populate the related records in both tables in the same transaction.
To create a one-to-one relationship, where Consecutives is the main table, Your DDL should look like this:
CREATE TABLE [dbo].[Consecutives]
(
[Consecutives_ID] [int] IDENTITY(1,1) NOT NULL,
[Name] [varchar](100) NULL,
[Value] [int] NOT NULL,
CONSTRAINT PK_Consecutives PRIMARY KEY (Consecutives_ID)
);
CREATE TABLE [dbo].[Users]
(
[User_ID] [int] NOT NULL,
[LogIn] [varchar](100) NULL,
[Pass] [varchar](100) NOT NULL,
CONSTRAINT PK_Users PRIMARY KEY (User_ID),
CONSTRAINT FK_Users_Consecutives FOREIGN KEY (User_ID) REFERENCES [dbo].[Consecutives]([Consecutives_ID])
);
Please note I've removed the identity specification from the User_ID column, and also changed the way the primary key is declared so that I could name it manually.
Naming constraints is best practice since if you ever need to change them it's much simpler when you already know their names.
Now, to insert a single record to both tables in the same transaction you can create a stored procedure like this:
CREATE PROCEDURE InsertUser
(
#Name varchar(100),
#Value int,
#LogIn varchar(100),
#Pass varchar(100)
)
AS
DECLARE #Consecutives AS TABLE
(
Id int
);
BEGIN TRY
BEGIN TRANSACTION
INSERT INTO [dbo].[Consecutives] ([Name], [Value])
OUTPUT Inserted.Consecutives_ID INTO #Consecutives
VALUES (#Name, #Value)
INSERT INTO [dbo].[Users] ([User_ID], [LogIn], [Pass])
SELECT Id, #Login, #Pass
FROM #Consecutives
COMMIT TRANSACTION
END TRY
BEGIN CATCH
IF ##TRANCOUNT > 0
ROLL BACK TRANSACTION
END CATCH
GO
and execute it like this:
EXEC InsertUser 'Zohar Peled', 1, 'Zohar', 'Peled'
You can see a live demo on rextester. (Please note that rextester doesn't allow using transactions so the try...catch and transaction parts are removed from the demo there)
Have you ever tried set identity insert on? This link may help you. To use the identity insert, the user needs some alter table permissions.

How do I insert data into a row in SQL?

I am following a tutorial and learning MVC from a book, where I was told to create a table using this script, which I did. But now I want to add an entire row to my Pet table, but I am unable to do it.
Script used to create all my tables.
CREATE TABLE [dbo].[Setting] (
[Id] INT NOT NULL IDENTITY(1, 1)
,[Key] VARCHAR(50) NOT NULL
,[Value] VARCHAR(500) NULL
,CONSTRAINT [PK_Setting] PRIMARY KEY ([Id])
);
CREATE TABLE [dbo].[PetType] (
[PetTypeID] INT NOT NULL IDENTITY(1, 1)
,[PetTypeDescription] VARCHAR(50) NULL
,CONSTRAINT [PK_PetType] PRIMARY KEY ([PetTypeID])
);
CREATE TABLE [dbo].[Status] (
[StatusID] INT NOT NULL IDENTITY(1, 1)
,[Description] VARCHAR(50) NOT NULL
,CONSTRAINT [PK_Status] PRIMARY KEY ([StatusID])
);
CREATE TABLE [dbo].[Pet] (
[PetID] INT NOT NULL IDENTITY(1, 1)
,[PetName] VARCHAR(100) NOT NULL
,[PetAgeYears] INT NULL
,[PetAgeMonths] INT NULL
,[StatusID] INT NOT NULL
,[LastSeenOn] DATE NULL
,[LastSeenWhere] VARCHAR(500) NULL
,[Notes] VARCHAR(1500) NULL
,[UserId] INT NOT NULL
,CONSTRAINT [PK_Pet] PRIMARY KEY ([PetID])
,CONSTRAINT [FK_Pet_Status] FOREIGN KEY ([StatusID]) REFERENCES [Status]([StatusID])
,CONSTRAINT [FK_Pet_User] FOREIGN KEY ([UserId]) REFERENCES [UserProfile]([UserId])
);
CREATE TABLE [dbo].[PetPhoto] (
[PhotoID] INT NOT NULL IDENTITY(1, 1)
,[PetID] INT NOT NULL
,[Photo] VARCHAR(500) NOT NULL CONSTRAINT [DF_PhotoFile] DEFAULT '/content/pets/no-image.png'
,[Notes] VARCHAR(500) NULL
,CONSTRAINT [PK_PetPhoto] PRIMARY KEY ([PhotoID])
,CONSTRAINT [FK_PetPhoto_Pet] FOREIGN KEY ([PetID]) REFERENCES [Pet]([PetID])
);
CREATE TABLE [dbo].[Message] (
[MessageID] INT NOT NULL
,[UserId] INT NOT NULL
,[MessageDate] DATETIME NOT NULL
,[From] VARCHAR(150) NOT NULL
,[Email] VARCHAR(150) NOT NULL
,[Subject] VARCHAR(150) NULL
,[Message] VARCHAR(1500) NOT NULL
,CONSTRAINT [PK_Message] PRIMARY KEY ([MessageID])
,CONSTRAINT [FK_Message_User] FOREIGN KEY ([UserId]) REFERENCES [UserProfile]([UserId])
);
I want to add some random values(for testing) into my Pet table's first row.
This is the Pet table's first row as an image for further clarity.
I tried using this script to add values to my table.
INSERT INTO Pet VALUES ('1', 'Fido', '12', '4', '1', '12/07/2004', 'New York', 'nothing', '1')
But I got an error saying
An explicit value for the identity column in table 'Pet' can only be specified when a column list is used and IDENTITY_INSERT is ON.
Now I am fairly new to SQL and I am unable to figure this out. I looked at other SO answers where people said something about SET IDENTITY_INSERT, but this didn't work for me as well. I believe I misunderstood other SO answer since I am fairly new to database languages. So need your help.
Thanks
In SQL Server identity is used for autoincrement. identity(1,1) means the starting value for the column will be 1 and will be incremented by 1. You can change it to desired value for example identity(5,2) starts the value at 5 and increments by 2. You no need to specify an explicit value for setting this column, it will be automatically assigned a unique value.
In mysql you can use AUTO_INCREMENT
Refer w3schools page for details sql autoincrement
PetID is defined as IDENTITY so you cannot specify a value to INSERT in that column unless you set "IDENTITY_INSERT" option to ON.
You have two options:
Dont specify that column/value and let SQL generate it for you.
Set IDENTITY_INSERT to ON before your INSERT operation.
Another very cool way to add rows/edit table (including editting deleting rows) is to use Microsoft SQL Management Studio Express. I didn't know about this until I'd been learning SQL for years. Basically expand the tree structure to the left, right-click on a table and choose Edit Table. When you get going with SQL more, you can edit Stored Procedures in here and pretty much anything SQL else you can can think of.
I've blurred out the actual database names but this gives you the gist of it :-

Composite Keys and Referential Integrity in T-SQL

Is it possible, in T-SQL, to have a relationship table with a composite key composed of 1 column defining Table Type and another column defining the Id of a row from a table referenced in the Table Type column?
For a shared-email address example:Three different user tables (UserA, UserB, UserC)One UserType Table (UserType)One Email Table (EmailAddress)One Email-User Relationship Table (EmailRelationship)The EmailRelationship Table contains three columns, EmailId, UserTypeId and UserId
Can I have a relationship from each User table to the EmailRelationship table (or some other way?) to maintain referential integrity?
I've tried making all three columns in the EmailRelationship table into primary keys, I've tried making only UserTypeId and UserId primary.
CREATE TABLE [dbo].[UserType](
[Id] [int] IDENTITY(1,1) NOT NULL ,
[Type] [varchar](50) NOT NULL)
insert into [dbo].[UserType]
([Type])
values
('A'),('B'),('C')
CREATE TABLE [dbo].[UserA](
[Id] [int] IDENTITY(1,1) NOT NULL,
[UserTypeId] [int] NOT NULL,
[Name] [varchar](50) NOT NULL)
insert into [dbo].[UserA]
(UserTypeId,Name)
values
(1,'UserA')
CREATE TABLE [dbo].[UserB](
[Id] [int] IDENTITY(1,1) NOT NULL,
[UserTypeId] [int] NOT NULL,
[Name] [varchar](50) NOT NULL)
insert into [dbo].[UserB]
(UserTypeId,Name)
values
(2,'UserB')
CREATE TABLE [dbo].[UserC](
[Id] [int] IDENTITY(1,1) NOT NULL,
[UserTypeId] [int] NOT NULL,
[Name] [varchar](50) NOT NULL)
insert into [dbo].[UserC]
(UserTypeId,Name)
values
(3,'UserC')
CREATE TABLE [dbo].[Email](
[Id] [int] IDENTITY(1,1) NOT NULL,
[EmailAddress] [varchar](50) NOT NULL)
insert into [dbo].[email]
(EmailAddress)
values
('SharedEmail#SharedEmail.com')
CREATE TABLE [dbo].[EmailRelationship](
[EmailId] [int] NOT NULL,
[UserTypeId] [int] NOT NULL,
[UserId] [int] NOT NULL)
insert into [dbo].[EmailRelationship]
(EmailId, UserTypeId, UserId)
values
(1,1,1),(1,2,1),(1,3,1)
No there isn't, a foreign key can refer to one table, and one table only, I can think of three ways you could approach this.
The first is to have 3 columns, one for each user table, each column with a foreign key, and a check constraint to check that at one, and only one of the values is not null
CREATE TABLE dbo.EmailRelationship
(
EmailId INT NOT NULL,
UserTypeId INT NOT NULL,
UserAId INT NULL,
UserBId INT NULL,
UserCId INT NULL,
CONSTRAINT FK_EmailRelationship__UserAID FOREIGN KEY (UserAId)
REFERENCES dbo.UserA (Id),
CONSTRAINT FK_EmailRelationship__UserBID FOREIGN KEY (UserBId)
REFERENCES dbo.UserB (Id),
CONSTRAINT FK_EmailRelationship__UserCID FOREIGN KEY (UserCId)
REFERENCES dbo.UserC (Id),
CONSTRAINT CK_EmailRelationship__ValidUserId CHECK
(CASE WHEN UserTypeID = 1 AND UserAId IS NOT NULL AND ISNULL(UserBId, UserCId) IS NULL THEN 1
WHEN UserTypeID = 2 AND UserBId IS NOT NULL AND ISNULL(UserAId, UserCId) IS NULL THEN 1
WHEN UserTypeID = 3 AND UserCId IS NOT NULL AND ISNULL(UserAId, UserBId) IS NULL THEN 1
ELSE 0
END = 1)
);
Then as a quick example trying to insert a UserAId with a user Type ID of 2 gives you an error:
INSERT EmailRelationship (EmailID, UserTypeID, UserAId)
VALUES (1, 1, 1);
The INSERT statement conflicted with the CHECK constraint "CK_EmailRelationship__ValidUserId".
The second approach is to just have a single user table, and store user type against it, along with any other common attributes
CREATE TABLE dbo.[User]
(
Id INT IDENTITY(1, 1) NOT NULL,
UserTypeID INT NOT NULL,
Name VARCHAR(50) NOT NULL,
CONSTRAINT PK_User__UserID PRIMARY KEY (Id),
CONSTRAINT FK_User__UserTypeID FOREIGN KEY (UserTypeID) REFERENCES dbo.UserType (UserTypeID),
CONSTRAINT UQ_User__Id_UserTypeID UNIQUE (Id, UserTypeID)
);
-- NOTE THE UNIQUE CONSTRAINT, THIS WILL BE USED LATER
Then you can just use a normal foreign key constraint on your email relationship table:
CREATE TABLE dbo.EmailRelationship
(
EmailId INT NOT NULL,
UserId INT NOT NULL,
CONSTRAINT PK_EmailRelationship PRIMARY KEY (EmailID),
CONSTRAINT FK_EmailRelationship__EmailId
FOREIGN KEY (EmailID) REFERENCES dbo.Email (Id),
CONSTRAINT FK_EmailRelationship__UserId
FOREIGN KEY (UserId) REFERENCES dbo.[User] (Id)
);
It is then no longer necessary to store UserTypeId against the email relationship because you can join back to User to get this.
Then, if for whatever reason you do need specific tables for different user types (this is not unheard of), you can create these tables, and enforce referential integrity to the user table:
CREATE TABLE dbo.UserA
(
UserID INT NOT NULL,
UserTypeID AS 1 PERSISTED,
SomeOtherCol VARCHAR(50),
CONSTRAINT PK_UserA__UserID PRIMARY KEY (UserID),
CONSTRAINT FK_UserA__UserID_UserTypeID FOREIGN KEY (UserID, UserTypeID)
REFERENCES dbo.[User] (Id, UserTypeID)
);
The foreign key from UserID and the computed column UserTypeID back to the User table, ensures that you can only enter users in this table where the UserTypeID is 1.
A third option is just to have a separate junction table for each User table:
CREATE TABLE dbo.UserAEmailRelationship
(
EmailId INT NOT NULL,
UserAId INT NOT NULL,
CONSTRAINT PK_UserAEmailRelationship PRIMARY KEY (EmailId, UserAId),
CONSTRAINT FK_UserAEmailRelationship__EmailId FOREIGN KEY (EmailId)
REFERENCES dbo.Email (Id),
CONSTRAINT FK_UserAEmailRelationship__UserAId FOREIGN KEY (UserAId)
REFERENCES dbo.UserA (Id)
);
CREATE TABLE dbo.UserBEmailRelationship
(
EmailId INT NOT NULL,
UserBId INT NOT NULL,
CONSTRAINT PK_UserBEmailRelationship PRIMARY KEY (EmailId, UserBId),
CONSTRAINT FK_UserBEmailRelationship__EmailId FOREIGN KEY (EmailId)
REFERENCES dbo.Email (Id),
CONSTRAINT FK_UserBEmailRelationship__UserBId FOREIGN KEY (UserBId)
REFERENCES dbo.UserB (Id)
);
Each approach has it's merits and drawbacks, so you would need to assess what is best for your scenario.
No it does not work that way. You cannot use a column value as a dynamic reference to different tables.
In general the data design is flawed.
Thanks to #GarethD I created a CHECK constraint that called a scalar-function that would enforce referential integrity (only upon insert, refer to caveat below):
Using my above example:
alter FUNCTION [dbo].[UserTableConstraint](#Id int, #UserTypeId int)
RETURNS int
AS
BEGIN
IF EXISTS (SELECT Id From [dbo].[UserA] WHERE Id = #Id and UserTypeId = #UserTypeId)
return 1
ELSE IF EXISTS (SELECT Id From [dbo].[UserB] WHERE Id = #Id and UserTypeId = #UserTypeId)
return 1
ELSE IF EXISTS (SELECT Id From [dbo].[UserC] WHERE Id = #Id and UserTypeId = #UserTypeId)
return 1
return 0
end;
alter table [dbo].[emailrelationship]
--drop constraint CK_UserType
with CHECK add constraint CK_UserType
CHECK([dbo].[UserTableConstraint](UserId,UserTypeId) = 1)
I am sure there is a not insignificant overhead to a Scalar-function call from within a CONSTRAINT. If the above becomes prohibitive I will report back here, though the tables in question will not have to deal with a large volume of INSERTs.
If there are any other reasons to not do the above, I would like to hear them. Thanks!
Update:
I've tested INSERT and UPDATE with 100k rows (SQL Server 2014, 2.1ghz quadcore w/ 8gb ram):
INSERT takes 2 seconds with out the CONSTRAINT
and 3 seconds with the CHECK CONSTRAINT
Turning on IO and TIME STATISTICS causes the INSERT tests to run in:
1.7 seconds with out the CONSTRAINT
and 10 seconds with the CHECK CONSTRAINT
I left the STATISTICS on for the UPDATE 100k rows test:
just over 1sec with out the CONSTRAINT
and 1.5sec with the CHECK CONSTRAINT
My referenced tables (UserA, UserB, UserC from my example) only contain around 10k rows each, so anybody else looking to implement the above may want to run some additional testing, especially if your referenced tables contain millions of rows.
Caveat:
The above solution may not be suitable for most uses, as the only time referential integrity is checked is during the CHECK CONSTRAINT upon INSERT. Any other operations or modifications of the data needs to take that into account. For example, using the above, if an Email is deleted any related EmailRelationship entries will be pointing to invalid data.

The INSERT statement conflicted with the FOREIGN KEY constraint

I searched for this kind of problem, but unfortunately didn't find any solution.
When I try to create a contact in my application I get an error
The INSERT statement conflicted with the FOREIGN KEY constraint "FK_Contacts_UserProfile". The conflict occurred in database "ContactAppContext", table "dbo.UserProfile", column 'UserId'.
I want to associate UserId with the Contacts table
My tables look like this:
CREATE TABLE [dbo].[Contacts] (
[ContactId] INT IDENTITY (1, 1) NOT NULL,
[UserId] INT NOT NULL,
[FirstName] NVARCHAR (MAX) NOT NULL,
[LastName] NVARCHAR (MAX) NOT NULL,
[Address] NVARCHAR (MAX) NOT NULL,
[City] NVARCHAR (MAX) NOT NULL,
[Phone] NVARCHAR (MAX) NOT NULL,
[Email] NVARCHAR (MAX) NOT NULL,
CONSTRAINT [PK_dbo.Contacts] PRIMARY KEY CLUSTERED ([ContactId] ASC),
CONSTRAINT [FK_Contacts_UserProfile] FOREIGN KEY ([UserId]) REFERENCES [dbo].[UserProfile] ([UserId])
);
CREATE TABLE [dbo].[UserProfile] (
[UserId] INT IDENTITY (1, 1) NOT NULL,
[UserName] NVARCHAR (56) NOT NULL,
PRIMARY KEY CLUSTERED ([UserId] ASC),
UNIQUE NONCLUSTERED ([UserName] ASC)
);
As you can see in the picture, UserId exists in UserProfile table
So what am I doing wrong?
EDIT 1
#Alexander Fedorenko
You mean this code?
SET IDENTITY_INSERT [dbo].[UserProfile] ON
INSERT INTO [dbo].[UserProfile] ([UserId], [UserName]) VALUES (1, N'admin')
INSERT INTO [dbo].[UserProfile] ([UserId], [UserName]) VALUES (2, N'test')
INSERT INTO [dbo].[UserProfile] ([UserId], [UserName]) VALUES (3, N'user')
SET IDENTITY_INSERT [dbo].[UserProfile] OFF
#Sachin How can I make sure, that when I try to insert in Contact table, it should be present in UserProfile table? I have, for example a user with UserId = 3, who is logged in and when he insert data, created contact would relate to that user.
EDIT 2
So when I created an editor field for UserId in the view, and it seems to be working, when I specify the UserId, and data is created, but I don't want this editor field for UserId in Create Contact page exist, because it is inconvenient that a user will write his UserId. So is it possible to relate UserId to logged in user, for example when he creates data, he doesn't need to specify his UserId, instead the record will be automatically saved to a database with his Id?
You need to either add data to UserProfile table first or to temporary disable foreign key constraint while data is inserted.
Your tables are set so that Contacts table is referencing UserProfile table therefore entry in UserProfile is needed in order to insert Contact.
Look at it this way: How can you know what is going to be UserID you want to enter in Contacts table if you don’t generate it in UserProfile table first?
Try to create the UserProfile table first and then the Contacts table.

Multilingual database design

I'm trying to design a database schema for a multilingual application. I have so far found a sample from this address. http://fczaja.blogspot.com/2010/08/multilanguage-database-design.html
But I haven't understood this sample. Should I insert Id value on app_product first? How can I know that these values are true for ProductId on app_product_translation?
CREATE TABLE ref_language (
Code Char(2)NOT NULL,
Name Varchar(20) NOT NULL,
PRIMARY KEY (Code)
);
CREATE TABLE app_product (
Id Int IDENTITY NOT NULL,
PRIMARY KEY (Id)
);
CREATE TABLE app_product_translation (
ProductId Int NOT NULL,
LanguageCode Char(2) NOT NULL,
Description Text NOT NULL,
FOREIGN KEY (ProductId) REFERENCES app_product(Id),
FOREIGN KEY (LanguageCode) REFERENCES ref_language(Code)
);
It looks like SQLServer code, proceeding on that assumption.
Yes you must insert the app_product first. But you cannot insert the id column's value. It is assigned automatically, because it is an identity column.
Two things you can check out...to find the identity column's value after inserting.
The OUTPUT clause of the INSERT statement. It can return any values that are inserted, not just the identity column.
The ##Identity variable. (by far more traditional and popular)
declare #lastid int
insert into x values (1,2,3)
set #lastid = ##identity
insert into y values (#lastid, a, b, c)