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
Related
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
I have two tables that's defined by the following:
CREATE TABLE Portfolio.DailyStats
(
Date date NOT NULL,
NAV int NOT NULL,
SP500 decimal(8,4) NULL,
R2K decimal(8,4) NULL,
NetExp decimal(8,4) NULL,
GrossExp decimal(8,4) NULL,
)
GO
CREATE TABLE Portfolio.DailyPortfolio
(
BbgID varchar(30) NOT NULL,
Ticker varchar(22) NULL,
Cusip char(9) NULL,
SecurityDescription varchar(50) NOT NULL,
AssetCategory varchar(25) NOT NULL,
LSPosition char(3) NULL,
Ccy varchar(25) NOT NULL,
Quantity int NULL,
DeltaExpNet int NULL,
Issuer varchar(48) NOT NULL,
Date date NOT NULL,
PortfolioID AS BbgID + LSPosition + Convert(varchar(8), Date, 112) Persisted Primary Key
)
GO
I am trying to create a view with 4 columns where I can see every Issuer, look at the dates when the Issuer appeared first and last in the DailyPortfolio table and the average NAV from the DailyStats table for those dates. So the first three columns of this view would be defined by:
SELECT
Issuer, MIN(Date) OpenDate, MAX(Date) CloseDate
FROM
Portfolio.DailyPortfolio
GROUP BY
Issuer
How do I add the fourth column that calculates the AverageNAV using the NAV column from the DailyStats table for the date range defined by the MIN(Date) and MAX(Date) columns in the view.
My final view should look something like this:
Issuer OpenDate CloseDate AverageNAV
:------|-----------|-----------|----------:
Issuer A 2/4/2015 11/9/2016 28234164
Issuer B 2/6/2015 5/19/2017 30446780
Issuer C 11/19/2015 10/11/2016 35789424
If you use a CTE to define the date range by issuer, you can use AVG to get an individual average base on each date range:
;WITH DateRange AS(
SELECT DP.Issuer, MIN(DP.Date) OpenDate, MAX(DP.Date) CloseDate
FROM Portfolio.DailyPortfolio DP
GROUP BY DP.Issuer
)
SELECT DR.Issuer, DR.OpenDate, DR.CloseDate, AVG(DS.NAV) AS AverageNAV
FROM DateRange DR
INNER JOIN Portfolio.DailyStats DS ON DS.Date BETWEEN DR.OpenDate AND DR.CloseDate
GROUP BY DR.Issuer, DR.OpenDate, DR.CloseDate
Here's full example code with sample data and output:
DECLARE #DailyStats TABLE
(Date DATE NOT NULL,
NAV INT NOT NULL)
DECLARE #DailyPortfolio TABLE
(Issuer VARCHAR(48) NOT NULL,
Date DATE NOT NULL)
INSERT INTO #DailyPortfolio VALUES ('Max', '1/1/2017')
INSERT INTO #DailyPortfolio VALUES ('Max', '2/1/2017')
INSERT INTO #DailyPortfolio VALUES ('Max', '3/1/2017')
INSERT INTO #DailyPortfolio VALUES ('Max', '4/1/2017')
INSERT INTO #DailyPortfolio VALUES ('Scott', '1/1/2015')
INSERT INTO #DailyPortfolio VALUES ('Scott', '2/1/2017')
INSERT INTO #DailyPortfolio VALUES ('Scott', '3/1/2017')
INSERT INTO #DailyPortfolio VALUES ('Scott', '4/1/2017')
INSERT INTO #DailyStats VALUES ('1/1/2016', 100)
INSERT INTO #DailyStats VALUES ('2/1/2017', 200)
INSERT INTO #DailyStats VALUES ('3/1/2017', 300)
INSERT INTO #DailyStats VALUES ('3/3/2017', 400)
;WITH DateRange AS(
SELECT DP.Issuer, MIN(DP.Date) OpenDate, MAX(DP.Date) CloseDate
FROM #DailyPortfolio DP
GROUP BY DP.Issuer
)
SELECT DR.Issuer, DR.OpenDate, DR.CloseDate, AVG(DS.NAV) AS AverageNAV
FROM DateRange DR
INNER JOIN #DailyStats DS ON DS.Date BETWEEN DR.OpenDate AND DR.CloseDate
GROUP BY DR.Issuer, DR.OpenDate, DR.CloseDate
Output:
Issuer OpenDate CloseDate AverageNAV
Max 2017-01-01 2017-04-01 300
Scott 2015-01-01 2017-04-01 250
I'm trying to create a trigger after an insert on the eventss table. The trigger should select the Bcoordinator_ID from the bookingCoordinator table where they have the minimum number of occurrences in the eventss table.
Here's my table data followed by the trigger. It doesn't like the minCount in the values, I think it's looking for and int.
DROP TABLE eventsBooking
CREATE TABLE eventsBooking
(
EBK INT NOT NULL IDENTITY(100, 1),
booking_ID AS 'EBK'+CAST( ebk as varchar(10)) PERSISTED PRIMARY KEY,
bookingDate DATE,
Bcoordinator_ID VARCHAR (20),
eventss_ID VARCHAR (20) NOT NULL
)
INSERT INTO eventsBooking
VALUES ('2015-01-07 11:23:00', NULL, 'EVT100');
Eventss table:
EVT INT NOT NULL IDENTITY(100, 1),
eventss_ID AS 'EVT' + CAST(evt as varchar(10)) PERSISTED PRIMARY KEY,
eventsName varchar(50),
noOfStages SMALLINT,
noOfRounds SMALLINT,
eventsDate DATE,
entryFee DECIMAL (7,2),
venue_ID VARCHAR (20) NOT NULL,
judges_ID VARCHAR (20)
INSERT INTO eventss
VALUES ('Swimming Gala 2015', '3', '7', '2015-01-07 09:00:00', '35.00', 'VEN101', 'JUD100');
CREATE TABLE bookingCoordinator
(
BCO INT NOT NULL IDENTITY(100, 1),
Bcoordinator_ID AS 'BCO'+CAST( bco as varchar(10)) PERSISTED PRIMARY KEY,
forename varchar(20) NOT NULL,
familyName varchar(50)
)
INSERT INTO bookingCoordinator VALUES ('Steve', 'Wills');
Trigger:
CREATE TRIGGER TRGinsertJudge
ON [dbo].[eventss]
AFTER INSERT
AS
BEGIN
SET NOCOUNT ON;
INSERT INTO dbo.eventsBooking (Bcoordinator_ID, bookingDate, Eventss_ID)
VALUES(minCount, getdate(), 100)
SELECT MIN(COUNT(Bcoordinator_ID)) AS minCount
FROM eventsBooking
END
You can't do an aggregation of an aggregation i.e. MIN(COUNT(1))
If you just want the Bcoordinatior_ID with the least counts in eventsBooking, do this
select top 1 bcoordinator_id
from eventsBooking
group by bcoordinator_id
order by count(1) asc
And you don't use VALUES() in an INSERT INTO ... SELECT statement
Also, in your current code, since eventsBooking.bcoordinator_id is always null, you need to join to the actual table of bookingCoordinators to return booking coordinators without any events booked.
So your complete trigger statement should be
INSERT INTO dbo.eventsBooking (Bcoordinator_ID, bookingDate, Eventss_ID)
select
top 1
bookingcoordinator.bcoordinator_id, getdate(), 100
from bookingCoordinator left join eventsBooking
on bookingCoordinator.Bcoordinator_ID = eventsBooking.Bcoordinator_ID
group by bookingcoordinator.bcoordinator_id
order by count(1) asc
I have a little strange issue with my SQL script and I was hoping someone could help me out with it.
I have a Database being created by using
IF EXISTS (SELECT name
FROM sysdatabases
WHERE name = 'travel')
DROP DATABASE travel
GO
CREATE DATABASE travel
GO
USE travel
GO
I then create 3 tables as shown below
CREATE TABLE customer
(
customerID INT,
lastname VARCHAR(70) NOT NULL,
firstname VARCHAR(70) NOT NULL,
phone VARCHAR(10) CONSTRAINT phoneCheck CHECK ((phone LIKE '[0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]')),
category VARCHAR(7) NOT NULL CONSTRAINT categoryDefault DEFAULT 'A',
CONSTRAINT categoryCheck CHECK (category IN ('A', 'B', 'C')),
CONSTRAINT customerPK
PRIMARY KEY (customerID)
)
CREATE TABLE package /*Still need to do the Zero Padding*/
(
packageCode VARCHAR(6),
destination VARCHAR(70),
CONSTRAINT packageCodeCheck CHECK (packageCode LIKE ('YFK%')),
price MONEY NOT NULL CONSTRAINT priceCheck CHECK ((price BETWEEN 1000 AND 10000)),
passportRequired VARCHAR(7) NOT NULL CONSTRAINT passportRequiredDefault DEFAULT 'Y',
CONSTRAINT passportCheck CHECK (passportRequired IN ('Y', 'N')),
CONSTRAINT packagePK
PRIMARY KEY (packageCode)
)
CREATE TABLE booking /*Still need to do the Customer and Package delete*/
(
customerID VARCHAR(6),
bookingDate VARCHAR(70) NOT NULL DEFAULT GETDATE(),
amountPaid MONEY CONSTRAINT amountPaidDefault DEFAULT 0.00,
CONSTRAINT bookingPK
PRIMARY KEY (customerID)
)
Now heres the issue, I create a trigger as shown below
GO
CREATE TRIGGER customerDelete ON customer AFTER DELETE
AS
DELETE booking
FROM customer
WHERE customer.customerID = booking.customerID
GO
Which to my understanding it will delete all records in booking... that have the matching customerID WHEN a record is deleted from the customer Table. (I am new to triggers)
I INSERT Sample Data as shown below
INSERT INTO customer
(customerID, lastname, firstname, phone, category)
VALUES
(1, 'Picard', 'Corey', 1234567890, 'A'),
(2, 'Bond', 'Devon', 9876543210, 'B'),
(3, 'Douglas', 'Bryan', 6549871230, 'C')
INSERT INTO package
(packageCode, destination, price, passportRequired)
VALUES
('YFK001', 'Toronto', 1000.57, 'N'),
('YFK002', 'Orlando', 3000.98, 'Y')
INSERT INTO booking
(customerID, bookingDate, amountPaid)
VALUES
(1, GETDATE(), 1548),
(2, GETDATE(), 1586),
(3, GETDATE(), 1350),
(4, GETDATE(), 1650)
And Finally I delete the Customer from the TABLE customer with the customerID of 1 by using
DELETE customer
WHERE customerID = 1
However, when I attempt to see the results by using
SELECT * FROM customer
--WHERE customerID = 1 OR customerID = 2 OR customerID = 3
SELECT * FROM package
--WHERE packageCode = 'YFK001' OR packageCode = 'YFK002'
SELECT * FROM booking
--WHERE customerID = 1 OR customerID = 2 OR customerID = 3 OR customerID = 4
It displays bookings with customerID 1 and 4.
Can you let me know what I'm doing wrong?
The trigger is essentially used for the purpose of deleting the bookings with the same customerID of the customer we delete from the customer TABLE
All help is greatly appreciated.
Thanks,
Bryan
Change your delete to this:
DELETE B
FROM booking B
INNER JOIN DELETED D
ON B.customerID = D.customerID;
My Answer is not trigger, [ If you specially want to use Trigger then You can use Lamak's & Pradeep's Answer]
Here best way you can do is use Cacade on foreign Key in your case
Here is your Query I just updated cascade in it
CREATE TABLE customer
(
customerID INT,
lastname VARCHAR(70) NOT NULL,
firstname VARCHAR(70) NOT NULL,
phone VARCHAR(10) CONSTRAINT phoneCheck CHECK ((phone LIKE '[0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]')),
category VARCHAR(7) NOT NULL CONSTRAINT categoryDefault DEFAULT 'A',
CONSTRAINT categoryCheck CHECK (category IN ('A', 'B', 'C')),
CONSTRAINT customerPK
PRIMARY KEY (customerID)
)
CREATE TABLE package /*Still need to do the Zero Padding*/
(
packageCode VARCHAR(6),
destination VARCHAR(70),
CONSTRAINT packageCodeCheck CHECK (packageCode LIKE ('YFK%')),
price MONEY NOT NULL CONSTRAINT priceCheck CHECK ((price BETWEEN 1000 AND 10000)),
passportRequired VARCHAR(7) NOT NULL CONSTRAINT passportRequiredDefault DEFAULT 'Y',
CONSTRAINT passportCheck CHECK (passportRequired IN ('Y', 'N')),
CONSTRAINT packagePK
PRIMARY KEY (packageCode)
ON DELETE CASCADE
ON UPDATE CASCADE
)
CREATE TABLE booking /*Still need to do the Customer and Package delete*/
(
customerID VARCHAR(6),
bookingDate VARCHAR(70) NOT NULL DEFAULT GETDATE(),
amountPaid MONEY CONSTRAINT amountPaidDefault DEFAULT 0.00,
CONSTRAINT bookingPK
PRIMARY KEY (customerID)
ON DELETE CASCADE
ON UPDATE CASCADE
)
This way when you are deleting or update [keyvalue] any entry of Table holding primary key will update its related foreign childs
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
)