tags:

views:

60

answers:

2

I am new to SQL and I need to build a database for a grocery store(not real, just a course assignment)

i have two fields from two different tables - supplied price - the price that the store buys from the supplier and price that is given to the customers

How can I make a constraint that insures that supplied price is lower then the price that is given to the customers?

The relevant tables that I have are:

CREATE TABLE Supplied_Products(
[Supplier ID]   Int NOT NULL  Foreign Key References Suppliers,
[Product ID]    Int NOT NULL Foreign Key References Products,
Price           Float NOT NULL,
CHECK (Price>0),
Constraint PK_Supplied_Products PRIMARY KEY([Supplier ID] ,[Product ID])
)
CREATE TABLE Products(
[Product-ID]    Int NOT NULL PRIMARY KEY,
[Product Name]  Varchar(20) NOT NULL,
Price           Float NOT NULL,
[Category-Name] Varchar(20) NOT NULL Foreign Key References Categories,
[Weight]        Float NOT NULL,
[Is Refrigirated] Varchar(1) DEFAULT 'N'
CHECK ([Is Refrigirated] in('Y','N')),/* Is Refrigirated can be only Y-yes or N-no*/
CHECK (Price >0)
)
+2  A: 

For MS SQL Server you can't use a CHECK constraint if you want to compare data in a different table.

In this scenario I would think an INSERT & UPDATE Trigger would be required to check the value being updated. You could then cancel the update/insert if the supplier price is more than the customer price.

Information on Triggers can be found here

Barry
No - For Homework they will likely just assume that these constraints are possible regardless of the lack of RDBMS support. At least that's what my course did!
Martin Smith
Really? What is the point in that? You are basically making it up as you go along.
Barry
@Barry - I think for my course it was because the SQL Standard does allow these. But actually his task does look considerably more concrete than just "write a check constraint" so your answer is probably more appropriate than I first thought.
Martin Smith
@Martin - I hope I didn't come across as having a go at you, just really threw me!
Barry
@Barry - No you definitely didn't. I agree with you.
Martin Smith
A: 

You can use stored procedures for inserting and altering rows in both tables which checks this constraint.

codymanix