Why is my SQL table not in 3 normal form - sql

I have made this database. It looks like it is working fine, except that I was told that my table "event" is not in third normal form. I do not see why it is not in the third normal form. I thought it is maybe because of the city and the zip code, which should be always the same, but large cities can have multiple zip codes and I do not see the point in creating another table just for the cities and their zip codes, related to the event table.
Also sorry if some of the names or attributes are named incorrectly by using some of the names reserved by the system. I had to translate the code to english, because I wrote it in my home language :). Thanks for your help.
Create table [article]
(
[id_article] Integer Identity(1,1) NOT NULL,
[id_author] Integer NOT NULL,
[id_category] Integer NOT NULL,
[title] Nvarchar(50) NOT NULL,
[content] Text NOT NULL,
[date] Datetime NOT NULL,
Primary Key ([id_article])
)
go
Create table [author]
(
[id_author] Integer Identity(1,1) NOT NULL,
[name] Nvarchar(25) NOT NULL,
[lastname] Nvarchar(25) NOT NULL,
[email] Nvarchar(50) NOT NULL, UNIQUE ([email]),
[phone] Integer NOT NULL, UNIQUE ([phone]),
[nick] Nvarchar(20) NOT NULL, UNIQUE ([nick]),
[passwd] Nvarchar(50) NOT NULL,
[acc_number] Integer NOT NULL, UNIQUE ([acc_number]),
Primary Key ([id_author])
)
go
Create table [event]
(
[id_event] Integer Identity(1,1) NOT NULL,
[id_author] Integer NOT NULL,
[name] Nvarchar(50) NOT NULL,
[date] Datetime NOT NULL, UNIQUE ([date]),
[city] Nvarchar(50) NOT NULL,
[street] Nvarchar(50) NOT NULL,
[zip] Integer NOT NULL,
[house_number] Integer NOT NULL,
[number_registered] Integer Default 0 NOT NULL Constraint [number_registered] Check (number_registered <= 20),
Primary Key ([id_event])
)
go
Create table [user]
(
[id_user] Integer Identity(1,1) NOT NULL,
[name] Nvarchar(15) NOT NULL,
[lastname] Nvarchar(25) NOT NULL,
[email] Nvarchar(50) NOT NULL, UNIQUE ([email]),
[phone] Integer NOT NULL, UNIQUE ([phone]),
[passwd] Nvarchar(50) NOT NULL,
[nick] Nvarchar(20) NOT NULL, UNIQUE ([nick]),
Primary Key ([id_user])
)
go
Create table [commentary]
(
[id_commentary] Integer Identity(1,1) NOT NULL,
[content] Text NOT NULL,
[id_article] Integer NOT NULL,
[id_author] Integer NULL,
[id_user] Integer NULL,
Primary Key ([id_commentary])
)
go
Create table [category]
(
[id_category] Integer Identity(1,1) NOT NULL,
[name] Nvarchar(30) NOT NULL,
Primary Key ([id_category])
)
go
Create table [registration]
(
[id_user] Integer NOT NULL,
[id_event] Integer NOT NULL,
Primary Key ([id_user],[id_event])
)
go
Alter table [commentary] add foreign key([id_article]) references [article] ([id_article]) on update no action on delete no action
go
Alter table [article] add foreign key([id_author]) references [author] ([id_author]) on update no action on delete no action
go
Alter table [event] add foreign key([id_author]) references [author] ([id_author]) on update no action on delete no action
go
Alter table [commentary] add foreign key([id_author]) references [author] ([id_author]) on update no action on delete no action
go
Alter table [registration] add foreign key([id_event]) references [event] ([id_event]) on update no action on delete no action
go
Alter table [commentary] add foreign key([id_user]) references [user] ([id_user]) on update no action on delete no action
go
Alter table [registration] add foreign key([id_user]) references [user] ([id_user]) on update no action on delete no action
go
Alter table [article] add foreign key([id_category]) references [category] ([id_category]) on update no action on delete no action
go
EDIT:
Do you think it could work like this? I made another table called location with all the address infos which were previously in event table and made the id_event PFK.
Create table [event]
(
[id_event] Integer Identity(1,1) NOT NULL,
[id_author] Integer NOT NULL,
[name] Nvarchar(50) NOT NULL,
[datr] Datetime NOT NULL,
[number_registered] Integer Default 0 NOT NULL Constraint [number_registered] Check (number_registered <= 20),
Primary Key ([id_event])
)
go
Create table [location]
(
[city] Char(1) NOT NULL,
[id_event] Integer NOT NULL,
[street] Char(1) NOT NULL,
[house_number] Char(1) NOT NULL,
[zip] Char(1) NOT NULL,
Primary Key ([id_event])
)
go
Alter table [event] add foreign key([id_auhtor]) references [author] ([id_author]) on update no action on delete no action
go
Alter table [location] add foreign key([id_event]) references [event] ([id_event]) on update no action on delete no action
go

To answer the question.
You are correct, the database is not in 3rd normal form. As you've identified there is an opportunity to normalise out the various postcodes, cities and streets. This would result in a row for each postcode (etc.) and you would have FKs for each.
Personally, I don't do this. It obviously depends on the application but in my systems I'm more interested in getting the address of the user rather than all the users who have a particular postcode.
Depending on how you intend to use your data 3rd normal may not be the most efficient way to store your data.

Based on your edit - close, but I'd turn it around. I'd give location a location_id column (PK), remove its event_id column, and then make event be:
Create table [event]
(
[id_event] Integer Identity(1,1) NOT NULL,
[id_author] Integer NOT NULL,
id_location Integer NOT NULL, /* Or null? does every event have to have a location */
[name] Nvarchar(50) NOT NULL,
[datr] Datetime NOT NULL,
[number_registered] Integer Default 0 NOT NULL Constraint [number_registered] Check (number_registered <= 20),
Primary Key ([id_event])
)
And then reverse the foreign key as well.
That way if an address requires correction it only needs to be corrected in one row - which is after all the point of normalization - making corrections only have to be applied once.

Related

Error during foreign key creation: Invalid references

I have 2 tables and I want to create a foreign key constraint in the second table. This is what I tried:
Table 1:
CREATE TABLE REMINDER_RULE_M
(
REMINDER_RULE_M_D int IDENTITY(1,1) NOT NULL,
COMMUNICATION_MODE nvarchar(255) NOT NULL,
REMINDER_TO nvarchar(255) NOT NULL,
REMINDER_VALUE varchar(255) NOT NULL,
REMINDER_CONDITION varchar(255) NOT NULL,
REMINDER_TO_CUSTOM varchar(255)
)
Table 2:
CREATE TABLE REMINDER_AUDIT
(
REMINDER_AUDIT_D int IDENTITY(1,1) NOT NULL,
ACTION varchar(255) NOT NULL,
CONSTRAINT FK_b892318b20e5bbe162722ea5946
FOREIGN KEY (REMINDER_RULE_M_D)
REFERENCES REMINDER_RULE_M(REMINDER_RULE_M_D),
OLD_VALUE nvarchar(1024) NOT NULL,
NEW_VALUE nvarchar(1024) NOT NULL,
)
I get an error running the second SQL query:
Reason:
SQL Error [1769] [S0001]: Foreign key 'FK_b892318b20e5bbe162722ea5946' references invalid column 'REMINDER_RULE_M_D' in referencing table 'REMINDER_AUDIT'.
As the error clearly tells you - you don't have a column in your second table.
You must have a column in order to create a FK constraint - the FK constraint does NOT create a column in your table - it just establishes a constraint between existing tables and columns.
So try this for your second table:
CREATE TABLE REMINDER_AUDIT
(
REMINDER_AUDIT_D int IDENTITY(1,1) NOT NULL,
ACTION varchar(255) NOT NULL,
-- define the column!
REMINDER_RULE_M_D int NOT NULL,
-- I'd strongly recommend trying to come up with a more
-- intuitive and useful naming convention for your FK constraints!
CONSTRAINT FK_b892318b20e5bbe162722ea5946
FOREIGN KEY (REMINDER_RULE_M_D)
REFERENCES REMINDER_RULE_M(REMINDER_RULE_M_D),
OLD_VALUE nvarchar(1024) NOT NULL,
NEW_VALUE nvarchar(1024) NOT NULL,
)
I just guessed that REMINDER_RULE_M_D is NOT NULL - you might need to adapt this (if it's an optional key).
You do not need to write Foreign Key
CREATE TABLE REMINDER_AUDIT (
REMINDER_AUDIT_D int IDENTITY(1,1) NOT NULL,
ACTION varchar(255) NOT NULL,
CONSTRAINT FK_b892318b20e5bbe162722ea5946 REFERENCES REMINDER_RULE_M(REMINDER_RULE_M_D),
OLD_VALUE nvarchar(1024) NOT NULL,
NEW_VALUE nvarchar(1024) NOT NULL,
)

Add a referential constraint with a constant value

I have a table of locations:
CREATE TABLE [dbo].[loca_location] (
[loca_id] [int] NOT NULL IDENTITY,
[loca_name] [nvarchar](100) NOT NULL,
[loca_address_line_1] [nvarchar](100),
[loca_address_line_2] [nvarchar](100),
[loca_address_line_3] [nvarchar](100),
[loca_address_town] [nvarchar](100),
[loca_address_county] [nvarchar](100),
[loca_post_code] [nvarchar](12),
[loca_active] [bit] NOT NULL,
[loca_created] [datetimeoffset](0) NOT NULL,
[loca_created_by] [nvarchar](50) NOT NULL,
[loca_modified] [datetimeoffset](0) NOT NULL,
[loca_modified_by] [nvarchar](50) NOT NULL,
[loca_deleted] [datetimeoffset](0),
[loca_deleted_by] [nvarchar](50),
[loca_type] [char](1),
CONSTRAINT [PK_dbo.loca_store] PRIMARY KEY ([loca_id])
)
Now some locations may be my own, others may be customers. If customer, then loca_type will be C. If I own it, it will be L. If its a supplier, then it will be S.
Now a contract should always belong to a customer, so I want to make it so the loca_type = C is a constraint as well as the loca_id.
ALTER TABLE [dbo].[cont_contract] ADD CONSTRAINT [FK_dbo.cont_contract_dbo.loca_location_cust_id] FOREIGN KEY ([loca_id_customer]) REFERENCES [dbo].[loca_location] ([loca_id], `C`)
That doesn't work. Is it possible to do what I want?
This may work
1.Declare UNIQUE ([loca_id], [loca_type] ) on [loca_location] table. That is correct as any superset of PK is unique.
2.Add constant column to [cont_contract] table.
3.Create FK.
CREATE TABLE [dbo].[loca_location] (
[loca_id] [int] NOT NULL IDENTITY,
--..
[loca_type] [char](1) CHECK ([loca_type] IN ('A','B','C')), -- change as needed
CONSTRAINT [PK_dbo.loca_store] PRIMARY KEY ([loca_id])
)
ALTER TABLE [dbo].[loca_location] ADD CONSTRAINT [u1] UNIQUE ([loca_id],[loca_type]);
CREATE TABLE [dbo].[cont_contract] (
[id] [int] NOT NULL IDENTITY,
--..
[loca_id_customer] Int,
-- Constant column
[loca_type] [char](1) DEFAULT 'C' CHECK ([loca_type] ='C')
);
ALTER TABLE [dbo].[cont_contract] ADD CONSTRAINT [FK_dbo.cont_contract_dbo.loca_location_cust_id]
FOREIGN KEY ([loca_id_customer],[loca_type]) REFERENCES [dbo].[loca_location] ([loca_id], [loca_type]);

checking foreign key in SQL, is it right? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
I need just little your help, can you just check if have I done foreign keys properly in SQL Server?
I'm new in SQL that is why sorry for stupid question.
If everything right, can I start to fill data?
--CREATING EMPLOYEE TABLE
CREATE TABLE EMPLOYEE(
[ID] INT IDENTITY(1,1) NOT NULL,
[FIRST_NAME] NVARCHAR(25) NOT NULL,
[LAST_NAME] NVARCHAR(25) NOT NULL,
[EMAIL] nvarchar(60) NOT NULL CONSTRAINT UQ_EMPLOYEE_email UNIQUE,
[PHARMACY_ID] INT NOT NULL,
CONSTRAINT PK_EMPLOYEE_ID PRIMARY KEY (ID));
--CREATING PHARMACY TABLE
CREATE TABLE PHARMACY (
[ID] INT IDENTITY(1, 1) NOT NULL,
[NAME] NVARCHAR(25),
[ADDRESS] NVARCHAR(25) NULL,
[PHONE] nvarchar(24) NULL CHECK(PHONE like '(___)-__-___ __ __'),
[EID] [INT] NOT NULL
CONSTRAINT PK_PHARMACY_ID PRIMARY KEY (ID));
--CREATE SUPPLIERS TABLE
CREATE TABLE SUPPLIERS(
[ID] INT IDENTITY(1,1) NOT NULL,
[NAME] NVARCHAR(25),
[ADDRESS] NVARCHAR(25) NULL,
[DRUGSID] [INT] NOT NULL,
CONSTRAINT PK_SUPPLIERS_ID PRIMARY KEY (ID));
--CREATE TABLE DRUGS
CREATE TABLE DRUGS(
[ID] INT IDENTITY(1,1) NOT NULL,
[NAME] NVARCHAR(25),
[QUANTITY] INT NULL,
[ORDERID] [INT] NULL,
[SUPPLIERID] [INT] NULL,
CONSTRAINT PK_DRUGS_ID PRIMARY KEY(ID));
--CREATEING TABLE ORDERS
CREATE TABLE ORDERS (
[ID] INT IDENTITY(1,1) NOT NULL,
[ONAME] NVARCHAR(25) NOT NULL,
[ODATE] DATETIME,
[OQUANTITY] INT NOT NULL,
[SUPPLIERID] [INT] NOT NULL,
[DRUGID] [INT] NOT NULL,
CONSTRAINT PK_ORDERS_ID PRIMARY KEY(ID));
--CREATING TABLE MANAGER TABLE
CREATE TABLE MANAGER (
[PASSPORTNO] INT IDENTITY(1,1) NOT NULL,
[HOURLYPAY] DECIMAL(5,2) NULL,
[LANGUAGE_SKILLS] NVARCHAR(25) NULL
CONSTRAINT PK_MANAGER_NO PRIMARY KEY (PASSPORTNO));
--CREATING TABLE SALES ASSISTANT
CREATE TABLE SALES_ASSISTANT (
[PASSPORTNO] INT IDENTITY(1,1) NOT NULL,
[SALARY] DECIMAL(5,2) NULL
CONSTRAINT PK_SALES_ASSISTANT_NO PRIMARY KEY (PASSPORTNO));
-- FOREIGN KEYs CREATION
ALTER TABLE EMPLOYEE ADD CONSTRAINT FK_PHARMACYID FOREIGN KEY(PHARMACY_ID)
REFERENCES PHARMACY(ID) ON DELETE CASCADE ON UPDATE CASCADE
ALTER TABLE PHARMACY ADD CONSTRAINT FK_EID FOREIGN KEY(EID)
REFERENCES EMPLOYEE(ID) ON DELETE NO ACTION ON UPDATE NO ACTION
ALTER TABLE SUPPLIERS ADD CONSTRAINT FK_DRUGID FOREIGN KEY(DRUGSID)
REFERENCES DRUGS(ID) ON DELETE NO ACTION ON UPDATE NO ACTION
ALTER TABLE DRUGS ADD CONSTRAINT FK_ORDERID FOREIGN KEY(ORDERID)
REFERENCES ORDERS(ID) ON DELETE NO ACTION ON UPDATE NO ACTION
ALTER TABLE DRUGS ADD CONSTRAINT FK_SUPPLIERS FOREIGN KEY(SUPPLIERID)
REFERENCES SUPPLIERS(ID) ON DELETE NO ACTION ON UPDATE NO ACTION
ALTER TABLE ORDERS ADD CONSTRAINT FK_SUPPLIERS_OR FOREIGN KEY(SUPPLIERID)
REFERENCES SUPPLIERS(ID) ON DELETE NO ACTION ON UPDATE NO ACTION
ALTER TABLE ORDERS ADD CONSTRAINT FK_DRUGID_OR FOREIGN KEY(DRUGID)
REFERENCES DRUGS(ID) ON DELETE NO ACTION ON UPDATE NO ACTION
You can check the foreign keys you have set with this query
SELECT
KCU1.CONSTRAINT_NAME AS FK_CONSTRAINT_NAME
,KCU1.TABLE_NAME AS FK_TABLE_NAME
,KCU1.COLUMN_NAME AS FK_COLUMN_NAME
,KCU1.ORDINAL_POSITION AS FK_ORDINAL_POSITION
,KCU2.CONSTRAINT_NAME AS REFERENCED_CONSTRAINT_NAME
,KCU2.TABLE_NAME AS REFERENCED_TABLE_NAME
,KCU2.COLUMN_NAME AS REFERENCED_COLUMN_NAME
,KCU2.ORDINAL_POSITION AS REFERENCED_ORDINAL_POSITION
FROM INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS AS RC
INNER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE AS KCU1
ON KCU1.CONSTRAINT_CATALOG = RC.CONSTRAINT_CATALOG
AND KCU1.CONSTRAINT_SCHEMA = RC.CONSTRAINT_SCHEMA
AND KCU1.CONSTRAINT_NAME = RC.CONSTRAINT_NAME
INNER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE AS KCU2
ON KCU2.CONSTRAINT_CATALOG = RC.UNIQUE_CONSTRAINT_CATALOG
AND KCU2.CONSTRAINT_SCHEMA = RC.UNIQUE_CONSTRAINT_SCHEMA
AND KCU2.CONSTRAINT_NAME = RC.UNIQUE_CONSTRAINT_NAME
AND KCU2.ORDINAL_POSITION = KCU1.ORDINAL_POSITION
One more thing:
Always create your scripts so you can run it N times if necessary.
So either drop the foreign key before you create it, or only create it if it doesn't exist. The same thing goes for the tables (don't drop them if they contain data).
Additionally, if you create a foreign key, you should check if all referenced tables exists, plus check that the referenced table has the primary key set.
Edit:
One tip, on a quick glare:
I would check if you really need DATETIME.
If you only need a date, use date instead of datetime.
That is how you do a FK but that data design does not look correct. You don't have an order point to a drug AND a drug point to an order. Read up on 3NF. A supplier does not have a single drug. DrugsID may have an S but it is still singular. This data design is not correct.

If the field was essentially changed, then change the value of one of its column

I have the essence of the "Requirements". If the user has changed the field "Description" in this instance, it should automatically change the value of the field "Stability" (dropdownlist). That is, if you had to change the description of the requirements, it becomes unstable. I wrote a trigger
CREATE TRIGGER [ChangeStabilityRequirement]
ON [dbo].[Requirement] AFTER UPDATE
AS
BEGIN
if update([Definition])
begin
update [Requirement] set Stability = 2
where RequirementId in (select RequirementId from inserted)
end
end
But the problem is that the trigger is activated when any change entries in the table. A need to respond only to changes in the column "Definition".
MY TABLE
CREATE TABLE [dbo].[Requirement] (
[RequirementId] INT IDENTITY (1, 1) NOT NULL,
[Rationale] NVARCHAR (MAX) NULL,
[CreatedOn] DATE CONSTRAINT [DF__Requireme__Creat__473C8FC7] DEFAULT (getdate()) NULL,
[CurentVersion] NVARCHAR (MAX) NULL,
[State] INT NOT NULL,
[Priority] INT NOT NULL,
[Type] INT NOT NULL,
[Source_BusinessRuleId] INT NULL,
[Stability] INT NOT NULL,
[UserPart] NVARCHAR (MAX) NULL,
[CreatedBy_UserId] INT NULL,
[Responsible_UserId] INT NULL,
[ImplementationVersion] NVARCHAR (MAX) NULL,
[ResponsibleId] INT DEFAULT ((0)) NULL,
[SourceId] INT DEFAULT ((0)) NULL,
[InterfacePoint_InterfacePointId] INT NULL,
[InterfacePointId] INT DEFAULT ((0)) NULL,
[CreatedById] INT DEFAULT ((0)) NULL,
[Definition] NVARCHAR (MAX) DEFAULT ('') NOT NULL,
CONSTRAINT [PK_dbo.Requirement] PRIMARY KEY CLUSTERED ([RequirementId] ASC),
CONSTRAINT [FK_dbo.Requirement_dbo.User_CreatedById] FOREIGN KEY ([CreatedById]) REFERENCES [dbo].[User] ([UserId]),
CONSTRAINT [FK_dbo.Requirement_dbo.User_ResponsibleId] FOREIGN KEY ([ResponsibleId]) REFERENCES [dbo].[User] ([UserId]),
CONSTRAINT [FK_dbo.Requirement_dbo.BusinessRule_SourceId] FOREIGN KEY ([SourceId]) REFERENCES [dbo].[BusinessRule] ([BusinessRuleId])
);
Update table
Updating occurs in a web application interface
This is query from SQL SERVER Profile
exec [dbo].[Requirement_Update]
#RequirementId=32,
#Definition=N'Реализовать возможность выбора значения "Без пени" в поле "Тип начисления пени". Диалоговое окно АР-12',
#Rationale=N'В соответствии с изменением бизнес-правила',
#CreatedOn='2014-12-18 00:00:00',
#CurentVersion=N'2.1',
#ImplementationVersion=N'2.2',
#State=0,
#Priority=1,
#Stability=1,
#Type=0
Ok, if you need update Requirement only when Definition is updated then change your trigger as:
CREATE TRIGGER [ChangeStabilityRequirement]
ON [dbo].[Requirement] AFTER UPDATE
AS
BEGIN
if update([Definition]) AND NOT update([Rationale]) AND NOT update([CurentVersion])
--AND NOT UPDATE(.....list here all possible columns that may be updated
begin
update [Requirement] set Stability = 2
where RequirementId in (select RequirementId from inserted)
end
end

How to reference two tables in Visual Studio 2012 by adding foreign key?

I have a problem adding a foreign key to a table column.
My tables look this way. I need to reference ContactOwnerId from Contact table to UserId in UserProfile table
CREATE TABLE [dbo].[Contacts] (
[ContactId] INT IDENTITY (1, 1) NOT NULL,
[ContactOwnerId] INT NOT NULL,
[FirstName] NVARCHAR (MAX) NOT NULL,
[LastName] NVARCHAR (MAX) NOT NULL,
[Address] NVARCHAR (MAX) NOT NULL,
[City] NVARCHAR (MAX) NOT NULL,
[Phone] NVARCHAR (MAX) NOT NULL,
[Email] NVARCHAR (MAX) NOT NULL,
CONSTRAINT [PK_dbo.Contacts] PRIMARY KEY CLUSTERED ([ContactId] ASC),
CONSTRAINT [FK_Contacts_UserProfile] FOREIGN KEY ([UserId]) REFERENCES [Contacts]([ContactOwnerId])
);
CREATE TABLE [dbo].[UserProfile] (
[UserId] INT IDENTITY (1, 1) NOT NULL,
[UserName] NVARCHAR (56) NOT NULL,
PRIMARY KEY CLUSTERED ([UserId] ASC),
UNIQUE NONCLUSTERED ([UserName] ASC)
);
I added a foreign key, but it seems, not right, because UserId is highlighted, giving error:
SQL71501 :: Foreign Key: [dbo].[FK_Contacts_UserProfile] has an unresolved reference to Column [dbo].[Contacts].[UserId].
SQL71516 :: The referenced table '[dbo].[Contacts]' contains no primary or candidate keys that match the referencing column list in the foreign key. If the referenced column is a computed column, it should be persisted.
How do I correctly reference these two tables? Thanks in advance.
EDIT
I did like sgeddes said. But I get an error, when I try to create a contact.
The INSERT statement conflicted with the FOREIGN KEY constraint "FK_Contacts_UserProfile". The conflict occurred in database "ContactAppContext", table "dbo.UserProfile", column 'UserId'.
The statement has been terminated.
If I remove a foreign key I get no error.
What I want to achieve is, when a user creates contacts, his Id(UserId) could associate with ContactOwnerId, so that contacts could relate to one specific user.
Since ContactOwnerId in the Contact table should be the FOREIGN KEY, you need to specify that in your CONSTRAINT instead of UserId.
I think this is what you're trying to do:
CREATE TABLE [dbo].[UserProfile] (
[UserId] INT IDENTITY (1, 1) NOT NULL,
[UserName] NVARCHAR (56) NOT NULL,
PRIMARY KEY CLUSTERED ([UserId] ASC),
UNIQUE NONCLUSTERED ([UserName] ASC)
);
CREATE TABLE [dbo].[Contacts] (
[ContactId] INT IDENTITY (1, 1) NOT NULL,
[ContactOwnerId] INT NOT NULL,
[FirstName] NVARCHAR (MAX) NOT NULL,
[LastName] NVARCHAR (MAX) NOT NULL,
[Address] NVARCHAR (MAX) NOT NULL,
[City] NVARCHAR (MAX) NOT NULL,
[Phone] NVARCHAR (MAX) NOT NULL,
[Email] NVARCHAR (MAX) NOT NULL,
CONSTRAINT [PK_dbo.Contacts] PRIMARY KEY CLUSTERED ([ContactId] ASC),
CONSTRAINT [FK_Contacts_UserProfile] FOREIGN KEY ([ContactOwnerId]) REFERENCES [UserProfile]([UserId])
);
The problem was with the last line. You need to reference the column from the Contacts table first, and then point to your UserProfile table. You had that backwards.
Here's a SQL Fiddle
Here's some documentation/examples for creating FOREIGN KEY CONSTRAINTS:
http://msdn.microsoft.com/en-us/library/aa258255(v=sql.80).aspx