The error I get is this "The INSERT statement conflicted with the FOREIGN KEY constraint "FK_vacation_users". The conflict occurred in database "TestAtt", table "dbo.users", column 'userID'."
I'm trying to insert into users with this:
INSERT into users (firstName, lastName, userName, password, team, fingerID, type, isActive) VALUES ('{0}', '{1}', '{2}', '{3}', '{4}', '{5}', '{6}', '{7}')",
firstNameAddBox.Text, lastNameAddBox.Text, userNameAddBox.Text, passwordAddBox.Text,
teamAddUserCombo.Text, fingerIdAddBox.Text, userTypeAddCombo.SelectedValue, isActiveCheck.Checked);
My users table looks like this:
CREATE TABLE
users
(
userID INT NOT NULL IDENTITY,
userName NVARCHAR(50) COLLATE Romanian_CI_AS NOT NULL,
password NVARCHAR(100) COLLATE Romanian_CI_AS NOT NULL,
firstName NVARCHAR(50) COLLATE Romanian_CI_AS NOT NULL,
lastName NVARCHAR(50) COLLATE Romanian_CI_AS NOT NULL,
team TINYINT NOT NULL,
type TINYINT NOT NULL,
fingerID SMALLINT NOT NULL,
isActive BIT DEFAULT 1 NOT NULL,
CONSTRAINT PK_users PRIMARY KEY (userID),
CONSTRAINT FK_users_userType FOREIGN KEY (type) REFERENCES userType (typeID),
CONSTRAINT users_idx UNIQUE (fingerID)
);
The vacation table looks like this:
CREATE TABLE
vacation
(
ID INT NOT NULL IDENTITY,
userID INT NOT NULL,
vacation TINYINT DEFAULT 0 NOT NULL,
extraDays TINYINT DEFAULT 0 NOT NULL,
PRIMARY KEY (ID),
CONSTRAINT FK_vacation_users FOREIGN KEY (ID) REFERENCES users (userID)
);
And this is the trigger:
ALTER TRIGGER "dbo"."newUserTrigger"
on "dbo"."users"
AFTER INSERT
as
begin
DECLARE #newUserID int
SELECT #newUserID = (SELECT userID FROM Inserted)
INSERT INTO vacation (userID) VALUES (#newUserID)
end;
So if I disable the trigger the insert works but with the trigger on it seems it wont insert the userID in the vacation table also.
I think your foreign key is incorrect, the column that's referencing users is userID, not ID:
CONSTRAINT FK_vacation_users FOREIGN KEY (userID) REFERENCES users (userID)
But your trigger is also broken because inserted can contain multiple (or no) rows. So it should be:
ALTER TRIGGER "dbo"."newUserTrigger"
on "dbo"."users"
AFTER INSERT
as
begin
INSERT INTO vacation (userID) SELECT userID from Inserted
end;
Here's the problem:
CONSTRAINT FK_vacation_users FOREIGN KEY (ID) REFERENCES users (userID)
This is saying that the ID column in vacation must have a matching value in userId in users. I think (ID) should be (userID). It should work OK then.
CONSTRAINT FK_vacation_users FOREIGN KEY (ID) REFERENCES users (userID)
should be
CONSTRAINT FK_vacation_users FOREIGN KEY (userID) REFERENCES users (ID)
Related
I have a very large CSV file I have to load on a regular basis that contains time series data. Examples of the headers are below:
| SiteName | Company | Date | ResponseTime | Clicks |
This data comes from a service external to the uploader. SiteName and Company are both string fields. In the database these are normalized. There is a Site table and a Company table:
CREATE TABLE [dbo].[Site] (
[Id] INT NOT NULL IDENTITY(1, 1) PRIMARY KEY,
[Name] NVARCHAR(MAX) NOT NULL
)
CREATE TABLE [dbo].[Company] (
[Id] INT NOT NULL IDENTITY(1, 1) PRIMARY KEY,
[Name] NVARCHAR(MAX) NOT NULL
)
As well as the data table.
CREATE TABLE [dbo].[SiteStatistics] (
[Id] INT NOT NULL IDENTITY(1, 1) PRIMARY KEY,
[CompanyId] INT NOT NULL,
[SiteId] INT NOT NULL,
[DataTime] DATETIME NOT NULL,
CONSTRAINT [SiteStatisticsToSite_FK] FOREIGN KEY ([SiteId]) REFERENCES [Site]([Id]),
CONSTRAINT [SiteStatisticsToCompany_FK] FOREIGN KEY ([CompanyId]) REFERENCES [Company]([Id])
)
At around 2 million rows in the CSV file any sort of IO-bound iteration isn't going to work. I need this done in minutes, not days.
My initial thought is that I could pre-load Site and Company into DataTables. I already have the CSV loaded into a datatable in the format that matches the CSV columns. I need to now replace every SiteName with the Id field of Site and every Company with the Id field of Company. What is the quickest, most efficient way to handle this?
If you go with Pre-Loading the Sites and Company's you can get the distinct values using code:
DataView view = new DataView(table);
DataTable distinctCompanyValues = view.ToTable(true, "Company")
DataView view = new DataView(table);
DataTable distinctSiteValues = view.ToTable(true, "Site")
Then load those two DataTables into their SQL Tables using Sql-Bulk-Copy.
Next dump all the data in:
CREATE TABLE [dbo].[SiteStatistics] (
[Id] INT NOT NULL IDENTITY(1, 1) PRIMARY KEY,
[CompanyId] INT DEFAULT 0,
[SiteId] INT DEFAULT 0,
[Company] NVARCHAR(MAX) NOT NULL,
[Site] NVARCHAR(MAX) NOT NULL,
[DataTime] DATETIME NOT NULL
)
Then do an UPDATE to set the Referential Integrity fields:
UPDATE [SiteStatistics] ss SET
[CompanyId] = (SELECT Id FROM [Company] c Where ss.[Company] = c.Name),
[SiteId] = (SELECT Id FROM [Site] s Where ss.[Site] = s.Name)
Add the Foreign Key constraints:
ALTER TABLE [SiteStatistics] ADD CONSTRAINT [SiteStatisticsToSite_FK] FOREIGN KEY ([SiteId]) REFERENCES [Site]([Id])
ALTER TABLE [SiteStatistics] ADD CONSTRAINT [SiteStatisticsToCompany_FK] FOREIGN KEY ([CompanyId]) REFERENCES [Company]([Id])
Finally delete the Site & Company name fields from SiteStatistics:
ALTER TABLE [SiteStatistics] DROP COLUMN [Company];
ALTER TABLE [SiteStatistics] DROP COLUMN [Site];
I have made a table named "reservations" which contains a customer id and a house id. I made tables for houses and customers as well. I have made a datagrid, which contains the reservations data, but I also want it to contain the customers surname and the house code.
My tables are (in SQL Server Express):
CREATE TABLE [dbo].[houses]
(
[Id] INT IDENTITY (1, 1) NOT NULL,
[Code] VARCHAR(50) NULL,
[Status] VARCHAR(50) NULL,
PRIMARY KEY CLUSTERED ([Id] ASC)
);
CREATE TABLE [dbo].[customers]
(
[Id] INT IDENTITY (1, 1) NOT NULL,
[Forename] VARCHAR(50) NULL,
[Surname] VARCHAR(50) NULL,
[Email] VARCHAR(50) NULL,
PRIMARY KEY CLUSTERED ([Id] ASC)
);
CREATE TABLE [dbo].[reservations]
(
[Id] INT IDENTITY (1, 1) NOT NULL,
[HouseId] INT NULL,
[CustomerId] INT NULL,
[StartDate] DATE NULL,
[EindDate] DATE NULL,
PRIMARY KEY CLUSTERED ([Id] ASC),
CONSTRAINT [FK_HouseId]
FOREIGN KEY ([HouseId]) REFERENCES [houses]([Id]),
CONSTRAINT [FK_CustomerId]
FOREIGN KEY ([CustomerId]) REFERENCES [customers]([Id])
);
I already created all the tables, but I don't know how to link them properly. I want to get the data and put it in a datagrid.
To select all data from Reservations, customers' Surname and house code, you need to run query:
Select R.*, C.Surname, H.Code
From [dbo].[reservations] R
inner join [dbo].[customers] C on C.Id = R.CustomerId
inner join [dbo].[houses] H on H.Id = R.HouseId
Try this:
select r.*,c.surname,h.code from reservation r,customers c,houses h where
r.customer_id=c.customer_id and r.house_id=h.house_id
I'm getting the following error when trying to insert values in the table:
INSERT statement conflicted with the FOREIGN KEY constraint "FK_BookingCustomer_Booking". The conflict occurred in database "C:\USERS\B00711882\SOURCE\WORKSPACES\SAILAWAY\SAILAWAY FINAL\SAILAWAYV2\SAILAWAYV2\APP_DATA\SAILAWAY.MDF", table "dbo.Booking", column 'ID'. The statement has been terminated.
My insert statement:
CREATE PROCEDURE [dbo].[inserBookingCustomer]
#customerID INT,
#bookingID INT
AS
INSERT INTO BookingCustomer (CustomerID, BookingID)
VALUES (#customerID, #bookingID)
RETURN 0
Table definitions:
Booking:
CREATE TABLE [dbo].[Booking]
(
[ID] INT IDENTITY (1, 1) NOT NULL,
[CharterID] INT NOT NULL,
[TotalCost] MONEY NOT NULL,
[StartDate] DATE NOT NULL,
[EndDate] DATE NOT NULL,
[TotalDays] INT NOT NULL,
CONSTRAINT [PK_Booking]
PRIMARY KEY CLUSTERED ([ID] ASC),
CONSTRAINT [FK_Booking_CharterID]
FOREIGN KEY ([CharterID]) REFERENCES [dbo].[Charter] ([ID])
);
BookingCustomer (where information should be inserted):
CREATE TABLE [dbo].[BookingCustomer]
(
[ID] INT IDENTITY (1, 1) NOT NULL,
[BookingID] INT NOT NULL,
[CustomerID] INT NOT NULL,
CONSTRAINT [PK_BookingCustomer]
PRIMARY KEY CLUSTERED ([ID] ASC),
CONSTRAINT [FK_BookingCustomer_Booking]
FOREIGN KEY ([BookingID]) REFERENCES [dbo].[Booking] ([ID]),
CONSTRAINT [FK_BookingCustomer_Customer]
FOREIGN KEY ([CustomerID]) REFERENCES [dbo].[Customer] ([CustomerID])
);
This is an ASP.Net application.
Edit: My c# code: https://pastebin.com/5a8seRh4
That is because you was tried to insert a value that no are inserted before in the Booking table.
You need to insert the book first and next insert the reference of the book with the customer
I need some guidance as to why i keep getting this error for my website every time I try to add a product. To let you know I did change the database around a bit, but after I did that i completely recreated the database. I keep getting the following error:
The INSERT statement conflicted with the FOREIGN KEY constraint "FK_dbo.OrderDetails_dbo.Orders_OrderId". The conflict occurred in database "MythData.mdf", table "dbo.Orders", column 'Id'.
the two tables are OrderDetail and Orders.
Order:
CREATE TABLE [dbo].[Orders]
(
[Id] INT IDENTITY (1, 1) NOT NULL,
[CustomerId] INT NOT NULL,
[ProductId] INT NOT NULL,
[ShipName] NVARCHAR (MAX) NULL,
[ShipAddress] NVARCHAR (MAX) NULL,
[ShipCity] NVARCHAR (MAX) NULL,
[ShipState] NVARCHAR (MAX) NULL,
[ShipZip] NVARCHAR (MAX) NULL,
CONSTRAINT [PK_dbo.Orders] PRIMARY KEY CLUSTERED ([Id] ASC),
CONSTRAINT [FK_dbo.Orders_dbo.Customers_CustomerId]
FOREIGN KEY ([CustomerId])
REFERENCES [dbo].[Customers] ([Id]) ON DELETE CASCADE
);
CREATE NONCLUSTERED INDEX [IX_CustomerId]
ON [dbo].[Orders]([CustomerId] ASC);
OrderDetail table:
CREATE TABLE [dbo].[OrderDetails]
(
[Id] INT IDENTITY (1, 1) NOT NULL,
[OrderId] INT NOT NULL,
[ProductId] INT NOT NULL,
[TotalCost] DECIMAL (18, 2) NOT NULL,
[SubTypeMail] BIT NOT NULL,
[Quantity] INT NOT NULL,
CONSTRAINT [PK_dbo.OrderDetails] PRIMARY KEY CLUSTERED ([Id] ASC),
CONSTRAINT [FK_dbo.OrderDetails_dbo.Orders_OrderId]
FOREIGN KEY ([OrderId])
REFERENCES [dbo].[Orders] ([Id]) ON DELETE CASCADE
);
CREATE NONCLUSTERED INDEX [IX_OrderId]
ON [dbo].[OrderDetails]([OrderId] ASC);
Also the class that the error is popping up in :
using (DataContext entities = new DataContext())
{
var orderDetail = entities.OrderDetails.Create();
decimal price = 0;
if (drpSub.SelectedValue == "Mailed")
{
price = 10;
orderDetail.SubTypeMail = true;
}
else
{
price = 5;
orderDetail.SubTypeMail = false;
}
Count = orderDetail.Quantity;
orderDetail.TotalCost = Count * price;
entities.OrderDetails.Add(orderDetail);
entities.SaveChanges(); << this line is the issue!
}
Also including exactly what the trace stated:
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.Data.SqlClient.SqlException: The INSERT statement conflicted with the FOREIGN KEY constraint "FK_dbo.OrderDetails_dbo.Orders_OrderId". The conflict occurred in database "MythData.mdf", table "dbo.Orders", column 'Id'.
Source Error:
Line 121: orderDetail.TotalCost = Count * price;
Line 122: entities.OrderDetails.Add(orderDetail);
Line 123: entities.SaveChanges();
Line 124: while (Count != 0)
Line 125: {
Source File: c:\Users\arielle davenport\Desktop\pets\pets\MythPetsDatabase\MythPetsDatabase\Pages\Products.aspx.cs Line: 123
I know this is long but any help is appreciated. Really stuck right now!
The error message is telling you exactly what the problem is: You're trying to insert a row that has a foreign key constraint to another table, and the value in that column does not exist in the other table.
Let's break it down:
The INSERT statement conflicted with the FOREIGN KEY constraint "FK_dbo.OrderDetails_dbo.Orders_OrderId".
The conflict occurred in database "MythData.mdf", table "dbo.Orders", column 'Id'.
It gives you the name of the constraint, so you can look at its definition if you need to. But the name pretty much tells you what you need to know... there's a constraint that the OrderId in the OrderDetails table has to match an Id in the Orders table. But the Orders table doesn't currently have an id that matches the one you're trying to insert into the OrderDetails table. It even tells you the problem is in the Orders Table, where the "id" column doesn't have a matching value for the row you're trying to insert into OrderDetails.
There are two potential causes:
1) There is a bug in your code which is trying to insert the wrong value into the id column in the OrderDetails table, or which is just failing to insert a row into the Order table at all
or more likely:
2) You're trying to insert rows in the wrong order... you need to insert the order into the Orders table BEFORE trying to insert the OrderDetails for that order.
You MUST make sure you have inserted the Order before you insert the OrderDetails, so that the critera of the Foreign Key Constaint is satisfied. This is precisely what FK Constraints are for: To prevent you from inserting inconsistent data, where certain values aren't valid (yet).
Hi ok I have two tables one called Login and one called User there is a one to one relationship from the user table to the login table:
Login:
=-=-=-=-
LoginID (Primary, Not Null, Auto Inc)
UserID (Primary)
Username (not null)
Password (not null)
User:
=-=-=-=-
UserID (Primary)
Email
Name etc
I cant get my head around it but I dont know when it comes to coding it on my page how the UserID is set in the Login table related to the actual user?
If I take the client to the create user page and he fills in the user details then I forward him to the username and password fields which goes to a different table how is the UserID set in the Login Table? Atm its not?
Incase any one wants to reverse engineer my table data in mysql eer diagram see code below:
SET #OLD_UNIQUE_CHECKS=##UNIQUE_CHECKS, UNIQUE_CHECKS=0;
SET #OLD_FOREIGN_KEY_CHECKS=##FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0;
SET #OLD_SQL_MODE=##SQL_MODE, SQL_MODE='TRADITIONAL';
CREATE SCHEMA IF NOT EXISTS `gymwebsite` DEFAULT CHARACTER SET latin1 COLLATE latin1_swedish_ci ;
USE `gymwebsite` ;
-- -----------------------------------------------------
-- Table `gymwebsite`.`User`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `gymwebsite`.`User` (
`UserID` INT NOT NULL AUTO_INCREMENT ,
`Email` VARCHAR(245) NULL ,
`FirstName` VARCHAR(45) NULL ,
`SecondName` VARCHAR(45) NULL ,
`DOB` VARCHAR(15) NULL ,
`Location` VARCHAR(45) NULL ,
`Aboutme` VARCHAR(245) NULL ,
PRIMARY KEY (`UserID`) )
ENGINE = InnoDB;
-- -----------------------------------------------------
-- Table `gymwebsite`.`Pictures`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `gymwebsite`.`Pictures` (
`PictureID` INT NOT NULL AUTO_INCREMENT ,
`UserID` INT NOT NULL ,
PRIMARY KEY (`PictureID`, `UserID`) ,
INDEX `fk_Pictures_Userinfo1` (`UserID` ASC) ,
CONSTRAINT `fk_Pictures_Userinfo1`
FOREIGN KEY (`UserID` )
REFERENCES `gymwebsite`.`User` (`UserID` )
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB;
-- -----------------------------------------------------
-- Table `gymwebsite`.`WallPostings`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `gymwebsite`.`WallPostings` (
`UserwallID` INT NOT NULL AUTO_INCREMENT ,
`UserID` INT NOT NULL ,
PRIMARY KEY (`UserwallID`, `UserID`) ,
INDEX `fk_WallPostings_Userinfo1` (`UserID` ASC) ,
CONSTRAINT `fk_WallPostings_Userinfo1`
FOREIGN KEY (`UserID` )
REFERENCES `gymwebsite`.`User` (`UserID` )
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB;
-- -----------------------------------------------------
-- Table `gymwebsite`.`Login`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `gymwebsite`.`Login` (
`LoginID` INT NOT NULL AUTO_INCREMENT ,
`UserID` INT NOT NULL ,
`username` VARCHAR(245) NOT NULL ,
`password` VARCHAR(45) NOT NULL ,
PRIMARY KEY (`LoginID`, `UserID`) ,
INDEX `fk_Login_Userinfo` (`UserID` ASC) ,
CONSTRAINT `fk_Login_Userinfo`
FOREIGN KEY (`UserID` )
REFERENCES `gymwebsite`.`User` (`UserID` )
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB;
-- -----------------------------------------------------
-- Table `gymwebsite`.`DietPlan`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `gymwebsite`.`DietPlan` (
`DietPlanID` INT NOT NULL AUTO_INCREMENT ,
`UserID` INT NOT NULL ,
PRIMARY KEY (`DietPlanID`, `UserID`) ,
INDEX `fk_DietPlan_Userinfo1` (`UserID` ASC) ,
CONSTRAINT `fk_DietPlan_Userinfo1`
FOREIGN KEY (`UserID` )
REFERENCES `gymwebsite`.`User` (`UserID` )
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB;
-- -----------------------------------------------------
-- Table `gymwebsite`.`WorkoutPlan`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `gymwebsite`.`WorkoutPlan` (
`WorkOutID` INT NOT NULL AUTO_INCREMENT ,
`UserID` INT NOT NULL ,
PRIMARY KEY (`WorkOutID`, `UserID`) ,
INDEX `fk_WorkoutPlan_Userinfo1` (`UserID` ASC) ,
CONSTRAINT `fk_WorkoutPlan_Userinfo1`
FOREIGN KEY (`UserID` )
REFERENCES `gymwebsite`.`User` (`UserID` )
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB;
-- -----------------------------------------------------
-- Table `gymwebsite`.`Friends`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `gymwebsite`.`Friends` (
`idFriends` INT NOT NULL AUTO_INCREMENT ,
`UserID` INT NOT NULL ,
PRIMARY KEY (`idFriends`, `UserID`) ,
INDEX `fk_Friends_Userinfo1` (`UserID` ASC) ,
CONSTRAINT `fk_Friends_Userinfo1`
FOREIGN KEY (`UserID` )
REFERENCES `gymwebsite`.`User` (`UserID` )
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB;
SET SQL_MODE=#OLD_SQL_MODE;
SET FOREIGN_KEY_CHECKS=#OLD_FOREIGN_KEY_CHECKS;
SET UNIQUE_CHECKS=#OLD_UNIQUE_CHECKS;
If User and Login has a 1:1 relation, you should drop LoginID from the Login table, and make UserID the primary key instead.
Or, if all users have login-information, you may consider moving the columns into the User table instead. (By doing so you also remove an entire class of problems related to enforcing 1-1 relations).
You should not insert any rows in the database until the user completes the entire registration form. Keep the form data in the session, and then at the end perform all inserts in all tables at once, then commit.
There is probably a function in c# to find out the last inserted id (UserID) to put in the Login table, otherwise have a look at the MySQL documentation for insert ID