I am trying to insert all the rows of cart Table of userId=1 into Order and OrderItem table the Order table consists of following columns:
ORDER TABLE
1.OrderId (int)
2.OrderDate(datetime)
3.userId (int)
4.orderStatus (varchar)
the user_tbltable is reference to the Order table with PK of userId and
cart table is also reference with userId
CART TABLE
Id
userId
Quantity
productID
ORDERITEM TABLE
id
orderid
productid
qty
ITEM Table
ProductId
Name
SizeId
ColorId
Price
Imageurl
I have tried following but this giving me conflict error:
The INSERT statement conflicted with the FOREIGN KEY constraint "FK_OrderItem_Item". The conflict occurred in database "db", table "dbo.Item", column 'Id'
insert into [Order] values(getdate(),#userId,#status);
set #orderId = ##IDENTITY
insert into OrderItem (OrderId ,ItemID,Qty,ColorId,SizeId)
select #orderId,Cart.ProductId,cart.Quantity,cart.ColorId,cart.SizeId
from [Cart]
where UserId=#userId ;
Change your Query as Below
INSERT INTO [Order]
VALUES
(
GETDATE(),
#userId,
#status
);
SELECT #orderId = SCOPE_IDENTITY();--Use SCOPE_IDENTITY Instead of ##IDENTITY
INSERT INTO OrderItem
(
OrderId,
ItemID,
Qty,
ColorId,
SizeId
)
SELECT [Order].OrderId,
Cart.ProductId,
cart.Quantity,
cart.ColorId,
cart.SizeId
FROM [Cart]
INNER JOIN [Order]
ON [Cart].UserId = #userId
AND [Order].OrderId = #orderId;--SELECT Order Id From Order to be more safer
Related
I have a table where the rows are duplicated. I would like to remove the duplicates and add a Composite Key to avoid duplicates.
;WITH myCTE (RowNumber, invoice_id, Invoice_Number, Organization_id, status, created_at) AS
(
SELECT
ROW_NUMBER() OVER (PARTITION BY Invoice_Number ORDER BY invoice_id, Invoice_Number DESC) AS RowNumber ,
invoice_id, Invoice_Number, Organization_id,status, created_at
FROM
Invoice_Export
)
SELECT *
FROM myCTE
WHERE Invoice_number LIKE '%-00%'
ORDER BY invoice_id
select * from Invoice_Export
ALTER TABLE Invoice_Export ALTER COLUMN [Organization_id] NVARCHAR(36) NOT NULL
ALTER TABLE Invoice_Export ALTER COLUMN [Invoice_Number] NVARCHAR(15) NOT NULL
ALTER table Invoice_Export
ADD CONSTRAINT [Composite_Key_Invoice] PRIMARY KEY CLUSTERED (Organization_id, Invoice_Number)
Is there any other better approach for the same.
I'm guessing that 'invoice_id' is unique, so
DELETE FROM Invoice_Export duplicate
WHERE EXISTS (SELECT 1 FROM Invoice_Export
WHERE duplicate.invoice_id > Invoice_Export.invoice_id
AND duplicate.Organization_id = Invoice_Export.Organization_id
AND duplicate.Invoice_Number = Invoice_Export.Invoice_Number)
instead PRIMARY KEY you can use UNIQUE (after removing duplicates)
ALTER TABLE Invoice_Export
ADD CONSTRAINT UC_Invoice_Export UNIQUE (Organization_id, Invoice_Number);
I have got thease three tables:
CREATE TABLE tblEmployee1
(
Id int Primary Key,
Name nvarchar(30),
Gender nvarchar(10),
DepartmentId int
)
CREATE TABLE tblDepartment1
(
DeptId int Primary Key,
DeptName nvarchar(20)
)
CREATE TABLE tblEmployee
(
Id int Primary Key,
Name nvarchar(30),
Gender nvarchar(10),
DepartmentId int,
DeptName nvarchar(20)
)
Two of them are joined by a view:
Create view ViewEmployeeDetails1
as
Select Id, Name, Gender,DepartmentId, DeptName
from tblEmployee1
join tblDepartment1
on tblEmployee1.DepartmentId = tblDepartment1.DeptId
I have created the trigger so that when the view is updated
with data trigger fires and update the third table (tblEmployee) with data in the view wihout duplicate record.
Trigger dosent seem to insert values on to the tblEmployee when the view is updated. Can you please help me with the trigger dont know where it's going
worng My trigger is below Thanks in advance.
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TRIGGER [dbo].[Update_Employee]
ON dbo.ViewEmployeeDetails1
INSTEAD OF UPDATE
AS
BEGIN
insert into dbo.tblEmployee
([Id], [Name], [Gender], [DepartmentId], [DeptName])
SELECT i.[Id],i.[Name], i.[Gender], i.[DepartmentId], i.[DeptName]
FROM dbo.ViewEmployeeDetails1 t
INNER JOIN i
ON t.Id = i.Id
WHERE i.Id IS NOT NULL
end
There is no DeptName in the table, so you would seem to want:
insert into dbo.tblEmployee ([Id], [Name], [Gender], [DepartmentId])
SELECT i.[Id], i.[Name], i.[Gender], i.[DepartmentId]
FROM inserted i
WHERE i.Id IS NOT NULL
end;
I've written the code to create a table and insert information from the Products table into the ProductsAudit table. My problem is that when I insert data into the Products table I get an error that tells me the DateUpdated column does not allow NULL values. I'm trying to insert GETDATE() and can't figure out what is causing the problem.
USE MyGuitarshop
GO
CREATE TABLE ProductsAudit(
AuditID int PRIMARY KEY IDENTITY,
ProductID int NOT NULL,
CategoryID int NOT NULL,
ProductCode varchar(10) NOT NULL,
ProductName varchar(255)NOT NULL,
ListPrice money NOT NULL,
DiscountPercent money NOT NULL,
DateUpdated datetime2 NOT NULL);
GO
CREATE TRIGGER ProductsAudit_UPDATE
ON Products
AFTER INSERT, UPDATE
AS
INSERT INTO
ProductsAudit (ProductID, CategoryID, ProductCode, ProductName, ListPrice, DiscountPercent, DateUpdated)
SELECT
Products.ProductID,
Products.CategoryID,
Products.ProductCode,
Products.ProductName,
Products.ListPrice,
Products.DiscountPercent,
DateAdded AS DateUpdated
FROM Products
GO
INSERT INTO
Products (CategoryID, ProductCode, ProductName, Description, ListPrice,DiscountPercent, DateAdded)
Values
(1, '229715', 'Sushi', 'Great food for hungry students', 9.99, 12, GETDATE());
GO
USE MyGuitarShop
SELECT * FROM ProductsAudit
I think you probably want AuditID to be an identity column:
CREATE TABLE ProductsAudit(
AuditID int IDENTITY PRIMARY KEY,
And once you've done that, you don't need to specify that column in the insert. You also probably meant to use getdate() for DateUpdated, especially since you're inserting null into the DateAdded column of Product.
INSERT INTO
ProductsAudit (ProductID, CategoryID, ProductCode, ProductName, ListPrice, DiscountPercent, DateUpdated)
SELECT
ProductID,
CategoryID,
ProductCode,
ProductName,
ListPrice,
DiscountPercent,
GetDate() AS DateUpdated
FROM INSERTED
Hopefully someone can help. I have created two tables Customer and Order as follows;
CREATE TABLE Customer
CustomerID int NOT NULL PRIMARY KEY
CustomerName varchar(25)
The other columns in Customer table are not relevant to my question, so I will not include them here. My CustomerID numbers are from 1 through to 15, all unique.
The second table I created is Orders as follows
CREATE TABLE Orders
OrderID smallint NOT NULL PRIMARY KEY
OrderDate date NOT NULL
CustomerID int FOREIGN KEY REFERENCES Customer (CustomerID);
My insert values is as follows
INSERT INTO Orders (OrderID, OrderDate, CustomerID)
VALUES
(1001, '2008-10-21', 1),
(1002, '2008-10-21', 8),
(1003, '2008-10-22', 15),
(1004, '2008-10-22', 5),
(1005, '2008-10-24', 3),
(1006, '2008-10-24', 2),
(1007, '2008-10-27', 11),
(1008, '2008-10-30', 12),
(1009, '2008-11-05', 4),
(1010, '2008-11-05', 1);
When I try to insert my values into the Order table, I get the following error message....
Msg 547, Level 16, State 0, Line 1.....The INSERT statement conflicted
with the FOREIGN KEY constraint "FK__OrderT__Customer__2D27B809". The
conflict occurred table "dbo.Customer", column 'CustomerID'. The
statement has been terminated.
The numbers for CustomerID in my Order table, are (1; 1; 2; 3; 4; 5; 8; 11; 12 and 15). Therefore I have checked that all my CustomerID numbers in Order table are also in the Customer table.
So my questions are
1) Has the insert values failed because my CustomerID column in Customer table in NOT NULL and I in error made CustomerID column NULL in Order.
2) If the answer to the above question is yes, then is it possible for me to (a) drop the foreign key on the CustomerID column in Order (b) change the column to NOT NULL and (c) then add the foreign key constraint again to this column and then insert the values again?
It might be easier to drop and re-create the table Order. But I am curious if option 2 would work, re dropping and adding a foreign key on the same column.
Hopefully I am on the right track with why I think the error occurred, feel
to correct me if I am wrong.
Thanks everyone
Josie
1) It should be NOT NULL in both. However error is because you attempted to insert a CustomerId that is not in Customer table.
2) You can simply alter the table and make it NOT NULL (error was not that).
Sample:
CREATE TABLE Customer
(
CustomerID INT NOT NULL
PRIMARY KEY ,
CustomerName VARCHAR(25)
);
CREATE TABLE Orders
(
OrderID INT NOT NULL
PRIMARY KEY ,
OrderDate DATE NOT NULL ,
CustomerID INT FOREIGN KEY REFERENCES Customer ( CustomerID )
);
INSERT [Customer] ( [CustomerID], [CustomerName] )
VALUES ( 1, 'Customer 1' ),
( 2, 'Customer 2' ),
( 3, 'Customer 3' ),
( 4, 'Customer 4' ),
( 5, 'Customer 5' ),
( 6, 'Customer 6' );
INSERT [Orders] ( [OrderID], [OrderDate], [CustomerID] )
VALUES
( 1, GETDATE(), 1 ),
( 2, GETDATE(), 2 ),
( 3, GETDATE(), 3 ),
( 4, GETDATE(), 4 ),
( 5, GETDATE(), 5 ),
( 6, GETDATE(), 6 );
INSERT [Orders] ( [OrderID], [OrderDate], [CustomerID] )
VALUES ( 7, GETDATE(), 7 );
Last one would error, because Customer with CustomerID 7 doesn't exist.
Update: I later saw your sample insert. You can find the offending ID like this:
DECLARE #ids TABLE ( id INT );
INSERT #ids ( [id] )
VALUES ( 1 ),
( 8 ),
( 15 ),
( 5 ),
( 3 ),
( 2 ),
( 11 ),
( 12 ),
( 4 ),
( 1 );
SELECT *
FROM #ids AS [i]
WHERE id NOT IN ( SELECT CustomerID
FROM [Customer] AS [c] );
1) Has the insert values failed because my CustomerID column in
Customer table in NOT NULL and I in error made CustomerID column NULL
in Order.
No. The error is not related to allowing NULL in the Order table. A NULL value will be allowed and not checked for referential integrity.
The foreign key violation error means you are attempting to insert a non-NULL CustomerID value into the Order table that does not exist in Customer. If you are certain the CustomerID values exist, perhaps the column mapping is wrong. Try specifying an explicit column list on the INSERT statement.
This error happens whern you are trying to insert a value in foreign key column, which this value does not exists in it's parent table. for example you are trying to insert value X to CustomerId in Order table, which this value does not exists in Customer table. This error occurred because we need to have a good strategy for Referential Integrity. So the only you need to do, is to check your new values(which you are going to insert them into table) to find out that is there any value compromising this rule or not.
However if you want to get an answer for your second question, you can try the below script:
create table t1
(
Id int primary key,
Name varchar(50) null
)
create table t2
(
Id int,
FK int null foreign key references t1(id)
)
go
alter table t2
alter column FK int not null
The identity column is set up once when you create the table.
The id assigned by an identity column start by the seed and are never reused.
So if you find that your customer ids starts from 6, it means that in the past you have added 5 customers and removed it.
If, for any reason, you want to use fixed Id don't use identity. In that case you take full responsability to set a unique value.
I suggest to never rely on fixed ids, if you must add orders from a script use the CustomerName (if unique), or any natural unique key.
You could use a script like this
DECLARE #newOrders TABLE (OrderID INT, CustomerName VARCHAR(25), OrderDate DATE);
INSERT INTO #newOrders (OrderID, CustomerName, OrderDate) VALUES
(1001, 'some-username', '2008-10-21'),
(1002, 'another-username', '2008-10-21');
INSERT INTO Orders(OrderID, CustomerId, OrderDate)
SELECT
o.OrderID,
c.CustomerID,
o.OrderDate
FROM #newOrders o
JOIN Customer c
ON c.CustomerName = o.CustomerName;
In this way you insert the correct CustomerID.
Note that in very rare cases (think twice to use it) you could insert values in identity colums using SET IDENTITY_INSERT statement.
I get this error when I try to generate data for my database:
Column name or number of supplied values does not match table definition
This is the structure of my database:
Create database Newsagents;
USE Newsagents;
CREATE TABLE Client (
ClientID int NOT NULL,
Name char(30) NOT NULL,
City char(20) DEFAULT NULL,
Type VARCHAR(15) NOT NULL CHECK (type IN('Individual', 'Company'))
PRIMARY KEY (ClientID)
) ;
CREATE TABLE Product (
ProductNumber char(10) NOT NULL,
ProductName char(20) NOT NULL,
Price float NOT NULL,
isAvailable tinyint NOT NULL,
PRIMARY KEY (ProductNumber)
) ;
CREATE TABLE Sales (
ID INT NOT NULL ,
ClientID INT REFERENCES Client(ClientID),
ProductNumber CHAR(10) REFERENCES Product(ProductNumber),
Quantity INT NOT NULL,
Price FLOAT NOT NULL ,
Date TIMESTAMP NOT NULL,
PRIMARY KEY ( ID )
);
ALTER TABLE sales ADD CONSTRAINT d CHECK (Date > CURRENT_TIMESTAMP);
ALTER TABLE sales ADD CONSTRAINT i CHECK (Quantity > 0);
I than fill my database with some values for Client and Product and I want to generate Sales (using values from Client and Product). This is how I do it:
DECLARE #counter INT
DECLARE #quantity int
DECLARE #prodNum varchar(20)
SET #counter = 0
WHILE #counter < 10
BEGIN
SET #quantity = (select FLOOR(RAND()*100))
SET #prodNum = (select TOP 1 ProductNumber from Product Order by NEWID())
insert into Sales values(
(select TOP 1 ClientID from Client Order by NEWID()),
(select #prodNum),
(select #quantity),
((select #quantity)*(select TOP 1 Price from Product where ProductNumber = #prodNum)),
DEFAULT
)
SET #counter = #counter + 1
END
However I get the Column name or number of supplied values does not match table definition.
What am I doing wrong?
You're not inserting anything into ID column of Sales. You need to specify it in your query:
insert into Sales values(
SomeIDHere,
(select TOP 1 ClientID from Client Order by NEWID()),
(select #prodNum),
(select #quantity),
((select #quantity)*(select TOP 1 Price from Product where ProductNumber = #prodNum)),
DEFAULT
)
But maybe you want to have an autoincrement column for your ID?
CREATE TABLE Sales (
ID INT IDENTITY(1,1) NOT NULL ,
ClientID INT REFERENCES Client(ClientID),
ProductNumber CHAR(10) REFERENCES Product(ProductNumber),
Quantity INT NOT NULL,
Price FLOAT NOT NULL ,
Date TIMESTAMP NOT NULL,
PRIMARY KEY ( ID )
);
In this case, you will need to specify the columns when inserting into Sales
insert into Sales (ClientID, ProductNumber, Quantity, Price, [Date])
values(
(select TOP 1 ClientID from Client Order by NEWID()),
(select #prodNum),
(select #quantity),
((select #quantity)*(select TOP 1 Price from Product where ProductNumber = #prodNum)),
DEFAULT
)