Stored procedure to insert a list of different types of items in to a table - sql

I have following two tables
CREATE TABLE Orders
(
OrderID int IDENTITY NOT NULL,
StaffID int NOT NULL,
TotalPrice money NOT NULL,
OrderDateTime dateTime NOT NULL
PRIMARY KEY (OrderID),
FOREIGN KEY (StaffID)
REFERENCES Staff(StaffID)
)
CREATE TABLE OrderDetails
(
OrderDetailID int IDENTITY NOT NULL,
OrderID int NOT NULL,
ItemID int,
ExtrasID int,
ItemQuantity int,
ExtrasQuantity int
PRIMARY KEY (OrderDetailID)
FOREIGN KEY (OrderID)
REFERENCES Orders(OrderID),
FOREIGN KEY (ExtrasID)
REFERENCES Extras(ExtrasID),
FOREIGN KEY (ItemID)
REFERENCES Item(ItemID)
)
I would like to create a stored procedure which will create a new order by inserting data in to both tables. This procedure should take the parameters for the StaffID, TotalPrice and the bought products. Products can be a many Items, many Extras or both.
Is there any way I can have a list of ItemID's and a list of ExtrasID's as the parameters which will then be inserted in to the OrderDetails table correctly?

Create a type first
CREATE TYPE dbo.ty_Product_Orders AS Table
(
ItemID INT
,ExtrasID INT
,ItemQuantity INT
,ExtrasQuantity INT
)
GO
Procedure Definition
Now make your procedure accept a parameter of that type.
CREATE PROCEDURE usp_Place_Order
#StaffID INT
,#TotalPrice MONEY
,#Order dbo.ty_Product_Orders READONLY
,#OrderPlaced BIT = 0 OUTPUT
AS
BEGIN
SET NOCOUNT ON;
-- table variable to hold the identity values
DECLARE #OrderDetails TABLE
(
OrderID INT,
ItemID INT
,ExtrasID INT
,ItemQuantity INT
,ExtrasQuantity INT
)
BEGIN TRY
BEGIN TRANSACTION;
-- Insert Orders
INSERT INTO Orders (StaffID , TotalPrice , OrderDateTime)
OUTPUT inserted.OrderID , inserted.ItemID ,inserted.ExtrasID ,
inserted.ItemQuantity ,inserted.ExtrasQuantity
INTO #OrderDetails(OrderID , ItemID , ExtrasID
,ItemQuantity ,ExtrasQuantity)
SELECT #StaffID , #TotalPrice , GETDATE()
FROM #Order
-- insert OrderDetails
INSERT INTO OrderDetails ((OrderID , ItemID , ExtrasID ,ItemQuantity ,ExtrasQuantity)
SELECT OrderID , ItemID , ExtrasID,ItemQuantity ,ExtrasQuantity
FROM #OrderDetails
COMMIT TRANSACTION;
END TRY
BEGIN CATCH
IF (##TRANCOUNT <> 0)
ROLLBACK TRANSACTION;
-- Other error logging here
END CATCH
END

Related

how to add a database constraint 18 or above

i have create a table and I need to add a database constraint "A customer with an age under 18 cannot rent a movie rated “18 or above”." How do I use SQL to add this in my table
You can use a trigger. When you want to enter information in the system to order a movie, do not allow the user to create a record if the age is less than the minimum required.
The following code snippet implements this scenario completely.
CREATE TABLE Customers
(
ID int identity,
FirstName nvarchar(100),
LastName nvarchar(100),
Age int,
primary key(ID))
CREATE TABLE Films
(
ID int identity,
FilmName nvarchar(100),
MinimumAge int,
primary key(ID))
CREATE TABLE OrderFilms
(
ID int identity,
CustomerID int,
FilmID int,
primary key(ID),
foreign key(CustomerID) references Customers,
foreign key(FilmID) references Films)
create trigger trigger_for_insert_into_OrderFilms
On OrderFilms
For Insert
AS
Declare #film int
Declare #customer int
Declare #filmage int
Declare #customerage int
set #film = (SELECT top 1 FilmID FROM inserted)
set #customer = (SELECT top 1 CustomerID FROM inserted)
set #filmage = (SELECT MinimumAge FROM Films WHERE ID = #film)
set #customerage = (SELECT Age FROM Customers WHERE ID = #customer)
IF(#filmage > 18 AND #customerage < 18)
BEGIN
PRINt 'ERROR, CUSTOMER AGE THE CUSTOMER IS YOUNG'
RollBack
END

How to trigger a table to change the value of another table column

I've created three tables.
CREATE TABLE Clients
(
ClientID INT IDENTITY(1,1) PRIMARY KEY,
First_Name VARCHAR(50) NOT NULL,
Last_Name VARCHAR(50) NOT NULL,
)
CREATE TABLE Reservation
(
ReservationID INT IDENTITY(1,1) PRIMARY KEY,
ClientID INT FOREIGN KEY (ClientID) REFERENCES Clients(ClientID),
Reservation_paid VARCHAR(3) DEFAULT 'NO',
)
CREATE TABLE Payment
(
Payment_ID INT IDENTITY(1,1) PRIMARY KEY,
ClientID INT FOREIGN KEY (ClientID) REFERENCES Clients(ClientID),
ReservationID INT FOREIGN KEY (ReservationID) REFERENCES Reservation(ReservationID),
)
I would like to change the value of the column Reservation_paid to YES at the Reservation table whenever the Client does pay the reservation, and i want to do it automatically with trigger.
Example: If the ClientID at the Reservation table exists at the Payment table automatically the value of the Reservation_paid will set to YES.
Thank you in advance.
CREATE TRIGGER trgAfterInsert ON [dbo].[Payment]
FOR INSERT
AS
declare #ClientID int;
select #ClientID =i.ClientID from inserted i;
if update(ClientID)
UPDATE Reservation set Reservation_paid='Yes' WHERE
ClientID=#ClientID;
--PRINT 'AFTER INSERT trigger fired.'
After Insert Trigger should do something like this
UPDATE R
SET Reservation_paid = 'Yes'
FROM reservation R
WHERE EXISTS (SELECT 1
FROM INSERTED I
WHERE I.clientid = R.clientid
AND I.reservationid = R.reservationid)
CREATE TRIGGER trgAfterInsert ON [dbo].[Payment]
FOR INSERT
AS
declare #ClientID int;
select #ClientID =i.ClientID from inserted i;
insert into Reservation(ClientID,Reservation_paid)
values(#ClientID,'Yes');
--PRINT 'AFTER INSERT trigger fired.'
GO
Write a trigger that will work on table Reservation after any insert or update on ClientId column of table Payment. Then match the ClientID with ClientID column of Reservation table and update the corresponding Reservation_paid to YES.
Edit:
The trigger will be like this
CREATE TRIGGER `UpdateReservation_paid` AFTER INSERT OR UPDATE ON `Payment`
FOR EACH ROW BEGIN
AS
begin
update Reservation
SET Reservation_paid='YES'
Where NEW.ClientID = Reservation.ClientID
and NEW.ReservationID = Reservation.ReservationID
end

how to create STORED PROCEDURE to insert data in two tables according to the CustomerID

CREATE
TABLE Customers(CustomerID int IDENTITY(1,1) PRIMARY KEY,FirstName nvarchar(45),LastName nvarchar(45),Address nvarchar(45))
CREATE
TABLE Orders(OrderID int IDENTITY(1,1) PRIMARY KEY,OrderDate date,CustomerID int FOREIGN KEY REFERENCES [dbo].[Customers](CustomerID))
CREATE
TABLE CustomersOrders(OrderID int FOREIGN KEY REFERENCES [dbo].[Orders](OrderID),ProductName nvarchar(45),Quantity nvarchar(45),Price nvarchar(45),TotalPrice int)
how to create STORED PROCEDURE in to insert data in Orders and CustomersOrders two tables according to the [dbo].Customers).
Customers table has entered data with 5 CustomerID
My Database is with first table parent and second is child . Third is the child of second table. I want to
insert data in last two tables according to the CustomerID. The data has to be added with that
particular customerid.
Try this
CREATE TABLE Customers
(
CustomerID INT IDENTITY(1, 1) PRIMARY KEY,
FirstName NVARCHAR(45),
LastName NVARCHAR(45),
Address NVARCHAR(45)
)
CREATE TABLE Orders
(
OrderID INT IDENTITY(1, 1) PRIMARY KEY,
OrderDate DATE,
CustomerID INT FOREIGN KEY REFERENCES [dbo].[Customers](CustomerID)
)
CREATE TABLE CustomersOrders
(
OrderID INT FOREIGN KEY REFERENCES [dbo].[Orders](OrderID),
ProductName NVARCHAR(45),
Quantity NVARCHAR(45),
Price NVARCHAR(45),
TotalPrice INT
)
DECLARE #FirstName NVARCHAR(45)='John',
#LastName NVARCHAR(45)='Smiths',
#Address NVARCHAR(45)='46 as str',
#OrderDate DATE=getdate(),
#ProductName NVARCHAR(45)='p1',
#Quantity NVARCHAR(45)='1',
#Price NVARCHAR(45)='30',
#TotalPrice INT=30
BEGIN
INSERT INTO Customers
(FirstName,
LastName,
Address)
VALUES (#FirstName,
#LastName,
#Address);
INSERT INTO Orders
(OrderDate,
CustomerID)
VALUES (#orderdate,
##IDENTITY)
INSERT INTO CustomersOrders
(OrderID,
ProductName,
Quantity,
Price,
TotalPrice)
VALUES (##IDENTITY,
#ProductName,
#Quantity,
#Price,
#TotalPrice)
SELECT *
FROM customers
SELECT *
FROM Orders
SELECT *
FROM CustomersOrders
END

How to add values of primary key column into foreign key column of other table

How to add values of primary key column into foreign key column of other table: I'm using SQL Server 2012
CREATE TABLE CUSTOMERS( ID INT NOT NULL, NAME VARCHAR (20) NOT NULL, AGE INT NOT NULL,
ADDRESS CHAR (25) , SALARY DECIMAL (18, 2), PRIMARY KEY (ID));
CREATE TABLE ORDERS ( ID INT NOT NULL, DATE DATETIME, CUSTOMER_ID INT references
CUSTOMERS(ID), AMOUNT VARCHAR (255), PRIMARY KEY (ID));
Here i need to take all values from primary key table 'customers' from column 'ID' to foreign key table orders to column 'ID'
DECLARE #A INT, #DATE DATETIME, #C_ID INT, #AMOUNTS INT;
SET #A =1;
SET #DATE ='2009-10-08 00:00:00';
SET #C_ID = 100
SET #AMOUNTS=1000;
WHILE #A <= 7
BEGIN
SET #DATE = DATEADD(DAY,1,#DATE);
SET #C_ID = #C_ID + 1
SET #AMOUNTS = #AMOUNTS+100;
INSERT INTO ORDERS(ID, DATE, CUSTOMER_ID,AMOUNT)
SELECT ID, #DATE, #C_ID, #AMOUNTS FROM CUSTOMERS WHERE AGE like'%';
SET #A = #A+1;
END
You have set your Orders table up with a Foreign Key on Customer_ID that references Customers(ID). So you can you only add rows to Orders if the ID exists in Customers. Right now you are trying to insert 101-107 in that column every time, so check if those IDs exists in Customers.
It seems to me that you SHOULD want to insert the Customers.ID column in Orders.Customer_ID, rather than Orders.ID. Is that what you meant?

Designing a rudimentary Shopping Cart database

create table [User]
(
UserId int primary key identity(1,1),
FirstName nvarchar(256) not null,
LastName nvarchar(256) not null,
)
create table Product
(
ProductId int primary key identity(1,1),
UnitPrice decimal(18,2) not null, //For catalog purposes.
Name nvarchar(1000) not null,
Description nvarchar(max) not null,
Stock int not null
)
create table [Order]
(
OrderId int primary key identity(1,1),
UserId int foreign key references [User](UserId),
ProductId int foreign key references Product(ProductId),
UnitCost decimal(18,2) not null, //How much it actually cost when the person bought it.
ItemCount int not null,
Subtotal decimal(18,2) not null
)
create table OrderDetail
(
OrderDetailId int primary key identity(1,1),
?
I'm stuck on the database design of the order system.
A user can choose n products to add to a order request. Any suggestions?
Following some advice given here, how would this feel? Any pitfalls?
create table [User]
(
UserId int primary key identity(1,1),
FirstName nvarchar(256) not null,
LastName nvarchar(256) not null,
)
create table Product
(
ProductId int primary key identity(1,1),
UnitPrice decimal(18,2) not null,
Name nvarchar(1000) not null,
Description nvarchar(max) not null,
Stock int not null
)
create table [Order]
(
OrderId int primary key identity(1,1),
UserId int foreign key references [User](UserId),
DateOfOrder datetime not null
)
create table OrderDetail
(
OrderDetailId int primary key identity(1,1),
OrderId int foreign key references [Order](OrderId),
ProductId int foreign key references Product(ProductId),
UnitCost decimal(18,2) not null,
ItemCount int not null,
Subtotal decimal(18,2) not null
)
Typically, you'd have the Order table with the top-level order information (who, when etc) and then an OrderItem (or OrderDetail) table which has a row for each product that forms part of the order including columns like:
OrderId
ProductId
Quantity
etc
Good candidate for a PK on this OrderItem/OrderDetail table would be on OrderId + ProductId.
So where you have columns like ProductId, UnitCost, ItemCount etc in the Order table, those are in the wrong place and should be in the OrderItem/OrderDetail table.
Update:
To set up a compound PK, you can do:
create table OrderDetail
(
OrderId int foreign key references [Order](OrderId),
ProductId int foreign key references Product(ProductId),
...other columns...,
CONSTRAINT PK_OrderDetail PRIMARY KEY(OrderId, ProductId)
)