SQL on Azure - using a computed column as a primary key index - sql

I am not sure what is wrong with the below SQL.
I used to have a primary key based off of the customer_reference_no.
They now have some duplicates so I am creating a column called uniquePoint that is a combination of customer_no, customer_reference_no and stop_zip.
The below works fine:
CREATE TABLE [dbo].[stop_address_details] (
[customer_no] NCHAR (5) NOT NULL,
[customer_reference_no] VARCHAR (20) NOT NULL,
[stop_name] VARCHAR (40) NOT NULL,
[stop_address] VARCHAR (40) NULL,
[stop_city] VARCHAR (30) NULL,
[stop_state] CHAR (2) NULL,
[stop_zip] VARCHAR (10) NULL,
[point_no] VARCHAR (20) NULL,
[branch_id] VARCHAR (6) NULL,
[delivery_route] VARCHAR (10) NULL,
[dateTimeCreated] DATETIME NULL,
[dateTimeUpdated] DATETIME NULL,
[estimated_delivery_time] TIME (0) NULL,
[est_del_time] DATETIME NULL,
[dateTimeLastUsedInDatatrac] DATETIME NULL,
[uniquePoint] as customer_no + '_' + customer_reference_no + '_' + stop_zip PERSISTED ,
CONSTRAINT [AK_stop_address_details_customer_reference_no] UNIQUE NONCLUSTERED ([customer_reference_no] ASC),
CONSTRAINT [PK_stop_address_details] PRIMARY KEY ([uniquePoint])
But when I remove the constraint for customer_reference_no I get the following error:
SQL71516 :: The referenced table '[dbo].[stop_address_details]' 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.
I am referencing the computed column and it is persisted.
Not sure what is missing?
Thank you,
Joe

The answer appears to be that I have another table that is referencing this table with a foreign key:
REATE TABLE [dbo].[rep_assigned_stop_matrix] (
[customer_reference_no] VARCHAR (20) NOT NULL,
[rep_id] INT NULL,
[dateTimeCreated] DATETIME NULL,
[sendSMS] BIT NULL,
[sendEmail] BIT NULL,
[id] INT IDENTITY (1, 1) NOT NULL,
CONSTRAINT [PK_rep_assigned_stop_matrix] PRIMARY KEY CLUSTERED ([id] ASC),
CONSTRAINT [AK_rep_assigned_stop_matrix_Column] UNIQUE NONCLUSTERED ([customer_reference_no] ASC, [rep_id] ASC),
CONSTRAINT [FK_pod_update_lookup_rep_info] FOREIGN KEY ([rep_id]) REFERENCES [dbo].[rep_info] ([id]) ON DELETE CASCADE,
CONSTRAINT [FK_lookup_Stop_Details] FOREIGN KEY ([customer_reference_no]) REFERENCES [dbo].[stop_address_details] ([customer_reference_no])
);
When this bottom constrain was removed the error went away. What I don't understand is why the error message was not a bit clearer (meaning naming the rep_assigned_stop_matrix table) -- or am I still missing something?
Joe

It seems that your '[dbo].[stop_address_details]' is still referring to the customer_reference_no column. Try Remove and re-add it using the new column name.

Related

The model already has an element that has the same name - ASP.NET

I'm working with ASP.Net web application and whenever I tried to add a FOREIGN KEY this error appears in the Data tools operations :
SQL71508 :: The model already has an element that has the same name
dbo.FK_Sellers_Users. SQL71508 :: The model already has an element
that has the same name dbo.FK_Sellers_Users.
I don't understand what's the problem with FK! I have 2 tables with this error
table Sellers :
CREATE TABLE [dbo].[Sellers] (
[Seller_ID] INT IDENTITY (1, 1) NOT NULL,
[Name] NVARCHAR (50) NOT NULL,
[SUsername] NVARCHAR (50) NOT NULL,
[Password] NVARCHAR (50) NOT NULL,
[SEmail] NVARCHAR (50) NOT NULL,
[Phone] NVARCHAR (50) NOT NULL,
[City] NVARCHAR (50) NOT NULL,
[LastLoginDate] DATETIME NULL,
[CreatedDate] DATETIME NULL,
PRIMARY KEY CLUSTERED ([Seller_ID] ASC),
CONSTRAINT [FK_Sellers_Users] FOREIGN KEY ([SEmail]) REFERENCES [Users]([Email]),
CONSTRAINT [FK_Sellers_Users] FOREIGN KEY ([SUsername]) REFERENCES [Users]([Username])
);
and table Users :
CREATE TABLE [dbo].[Users] (
[Id] INT NOT NULL IDENTITY,
[Username] NVARCHAR (50) NOT NULL,
[Password] NVARCHAR (50) NOT NULL,
[Email] NVARCHAR (50) NOT NULL,
[UserType] INT NULL,
PRIMARY KEY CLUSTERED ([Id]),
CONSTRAINT [AK_Users_Username] UNIQUE ([Username]),
CONSTRAINT [AK_Users_Email] UNIQUE ([Email]),
);
Right there in your CREATE TABLE statement for dbo.Sellers, you have two FK constraints named FK_Sellers_Users.
Make those names unique, perhaps by adding the column name on the end.
You have two foreign keys with the same name FK_Sellers_Users. You should better use FK_Sellers_Users_Email and FK_Sellers_Users_Username.
Actually, this has to do with data that was already entered. Some of the PK and FK data that were entered before might have the same values. You need to delete those first and make the changes you need.
If your project uses SSDT (SQL Server Data Tools), you probably have a foreign key defined in a folder for Keys. Look in "DB Name\Schema Objects\Schemas\dbo\Tables\Keys."
Then Look in the table definition. "DB Name\Schema Objects\Schemas\dbo\Tables". The key could be defined in BOTH places.

SQL Syntax error with foreign keys

now i have table place CREATE TABLE [dbo].[Place] (
[Place_Id] INT IDENTITY (1, 1) NOT NULL,
[Name] VARCHAR (50) NOT NULL,
[Building_Date] DATE NULL,
[Longitude] VARCHAR (50) NULL,
[Latitude] VARCHAR (50) NULL,
[Location] VARCHAR (50) NOT NULL,
PRIMARY KEY CLUSTERED ([Place_Id] ASC)
); , and table Citeria CREATE TABLE [dbo].[Criteria] (
[Criteria] VARCHAR (50) NOT NULL,
[Place_Id] INT NOT NULL, PRIMARY KEY CLUSTERED ([Criteria], [Place_Id]), CONSTRAINT [FK_Criteria_ToTable] FOREIGN KEY (Place_Id) REFERENCES Place(Place_Id)
);and The referenced table '[dbo].[Criteria]' 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.
.
The error is correct. Subqueries are not allowed in check constraints.
But, you already have a foreign key reference between user_name and likes(user_name), so this condition is already in place. The only thing is would really be checking is that user_name is not NULL, but that is already true by the definition of the column.
Now, there are other issues. Your foreign keys should be to primary keys or unique keys in other tables. I think this is your intention:
CREATE TABLE [dbo].Normal_Upload
(
[User_Name] VARCHAR(50) NOT NULL ,
[Place_Id] INT NOT NULL,
[Image] IMAGE NOT NULL,
CONSTRAINT [FK_Normal_Upload] FOREIGN KEY (User_Name) REFERENCES Member(User_Name),
CONSTRAINT [FK_Normal_Upload_1] FOREIGN KEY (Place_Id) REFERENCES Place(Place_Id),
CONSTRAINT [FK_Normal_Upload_2] FOREIGN KEY (User_Name, Place_Id) REFERENCES Likes(User_Name, Place_Id)
);
As a note on naming. I think the primary keys of tables should include the table name. So, consider Member_Name rather than User_Name for the Member table.
It wrong db design, never use varchar or character type column in reference key or primary-key(try to avoid as much as possible).
For you solution, create a column "useid" with int datatype and give pk to it. and update the following table
CREATE TABLE [dbo].[Likes] (
[User_id] VARCHAR (50) Identity (1,1),
[User_Name] VARCHAR (50) NOT NULL,
[Place_Id] INT NOT NULL,
CONSTRAINT [PK_Likes] PRIMARY KEY CLUSTERED ([User_id] ASC, [Place_Id] ASC),
CONSTRAINT [FK_Likes_ToTable] FOREIGN KEY ([User_Name]) REFERENCES Normal ([User_Name]),
CONSTRAINT [FK_Likes_ToTable_1] FOREIGN KEY ([Place_Id]) REFERENCES [dbo].[Place] ([Place_Id]),
);

Error creating table in oracle

I am trying to create a table in oracle but I am getting this error: unknown command ")" - rest of line ignored. I can't figure out what is causing this error. Below is my SQL for the table:
CREATE TABLE PAYMENT
(PayNum INT NOT NULL PRIMARY KEY,
CType VARCHAR(1) NOT NULL,
CCNum VARCHAR(16) NOT NULL,
BankName VARCHAR(75) NOT NULL,
AccNum INT NOT NULL,
PDate DATE NOT NULL,
Amt DECIMAL(11,2) NOT NULL,
CONSTRAINT fk_BANKACC_PAYMENT FOREIGN KEY (BankName, AccNum)
REFERENCES BANKACC(BankName, AccNum),
CONSTRAINT fk_CRCARD_PAYMENT FOREIGN KEY (CType, CCNum)
REFERENCES CRCARD(CType, CCNum)
);
Your code is correct. Make sure you are referencing primary keys (all 4).
Check this: http://sqlfiddle.com/#!2/7be70/1/0
If you do not follow that, you may get this error: There are no primary or candidate keys in the referenced table 'BANKACC' that match the referencing column list in the foreign key 'fk_BANKACC_PAYMENT'.
Code in the fiddle above:
CREATE TABLE BANKACC
(BankName VARCHAR(75) NOT NULL,
AccNum INT NOT NULL,
PRIMARY KEY(BankName, AccNum));
CREATE TABLE CRCARD
(CType VARCHAR(1) NOT NULL,
CCNum VARCHAR(16) NOT NULL,
PRIMARY KEY(CType, CCNum));
CREATE TABLE PAYMENT
(PayNum INT NOT NULL PRIMARY KEY,
CType VARCHAR(1) NOT NULL,
CCNum VARCHAR(16) NOT NULL,
BankName VARCHAR(75) NOT NULL,
AccNum INT NOT NULL,
PDate DATE NOT NULL,
Amt DECIMAL(11,2) NOT NULL,
CONSTRAINT fk_BANKACC_PAYMENT FOREIGN KEY (BankName, AccNum)
REFERENCES BANKACC(BankName, AccNum),
CONSTRAINT fk_CRCARD_PAYMENT FOREIGN KEY (CType, CCNum)
REFERENCES CRCARD(CType, CCNum)
);
Also you should read this for better understanding on how to implement foreign key constraint: http://docs.oracle.com/cd/E17952_01/refman-5.5-en/create-table-foreign-keys.html
If you're running this in SQL*Plus, get rid of the blank line between REFERENCES and ):
REFERENCES CRCARD(CType, CCNum)
);
Or set sqlblanklines on to change the behaviour.
By default it interprets a blank line as the end of the statement, but doesn't run it. So your entire CREATE TABLE command is essentially ignored, and the ); is treated as a stanalone command. Hence the error message you get, since it doesn't mean anything on its own.
Please use NUMBER for numeric columns.
http://docs.oracle.com/cd/B28359_01/server.111/b28318/datatype.htm#CNCPT313
Also, in Oracle, use VARCHAR2 for strings.
but of it your syntax should be correct.

Error Defining Foreign Key

I have the following two database tables defined:
CREATE TABLE [dbo].[Classrooms] (
[ID] INT IDENTITY (1, 1) NOT NULL,
[SystemAccount_ID] INT NOT NULL,
[ClassroomName] VARCHAR (30) NOT NULL,
CONSTRAINT [PK_Table] PRIMARY KEY CLUSTERED ([ID]),
CONSTRAINT [FK_Classrooms_SystemAccount] FOREIGN KEY ([SystemAccount_ID]) REFERENCES [dbo].[SystemAccounts] ([ID])
);
CREATE TABLE [dbo].[Students] (
[ID] INT IDENTITY (1, 1) NOT NULL,
[SystemAccount_ID] INT NOT NULL,
[Classroom_ID] INT NULL,
[PhotoID] INT NULL,
[FirstName] VARCHAR (20) NOT NULL,
[LastName] VARCHAR (40) NOT NULL,
[NewsTemplate] TINYINT NOT NULL,
CONSTRAINT [PK_Students] PRIMARY KEY CLUSTERED ([ID] ASC),
CONSTRAINT [FK_Students_Classrooms] FOREIGN KEY ([Classroom_ID]) REFERENCES [dbo].[Classrooms] ([ID]),
CONSTRAINT [FK_Students_SystemAccounts] FOREIGN KEY ([SystemAccount_ID]) REFERENCES [dbo].[SystemAccounts] ([ID])
);
Data model details:
Students belong to zero or one classroom via Classroom_ID FK
Students belong to one System Account via SystemAccount_ID FK
Classrooms belong to one System Account via SystemAccount_ID FK (implying a system account can have zero or more Classrooms)
What I'm attempting to do is enforce when students are added to a classroom (by setting the Classroom_ID key in the Students table) that the classroom belongs to the same system account as the student. I could easily enforce this at the business logic layer but then I'd be requiring every programmer to remember to do this. So ideally, I'd be able to do this at the data layer as a constraint.
I tried adding a FK constraint to the Students table:
CONSTRAINT [FK_Students_ToTable] FOREIGN KEY ([SystemAccount_ID]) REFERENCES [Classrooms]([SystemAccount_ID])
Which results in the following error compliments of SQL Server:
Update cannot proceed due to validation errors.
Please correct the following errors and try again.
SQL71516 :: The referenced table '[dbo].[Classrooms]' 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.
I've tried a few different things but my SQL mojo isn't powerful enough to hack past this one. Any help would be greatly appreciated.
Add a UNIQUE constraint on the combination of the two columns in Classrooms:
CREATE TABLE [dbo].[Classrooms] (
[ID] INT IDENTITY (1, 1) NOT NULL,
[SystemAccount_ID] INT NOT NULL,
[ClassroomName] VARCHAR (30) NOT NULL,
CONSTRAINT [PK_Table]
PRIMARY KEY CLUSTERED ([ID]),
CONSTRAINT [FK_Classrooms_SystemAccount]
FOREIGN KEY ([SystemAccount_ID])
REFERENCES [dbo].[SystemAccounts] ([ID]),
CONSTRAINT [UQ_Classrooms_ID_SystemAccount_ID]
UNIQUE ([SystemAccount_ID], [ID])
);
Then, in the Students table, combine the two FOREIGN KEY constraints into one, or in your case (because Classroom_ID isnullable), change the FK to Classroom to use the combination of the two columns:
CREATE TABLE [dbo].[Students] (
[ID] INT IDENTITY (1, 1) NOT NULL,
[SystemAccount_ID] INT NOT NULL,
[Classroom_ID] INT NULL,
[PhotoID] INT NULL,
[FirstName] VARCHAR (20) NOT NULL,
[LastName] VARCHAR (40) NOT NULL,
[NewsTemplate] TINYINT NOT NULL,
CONSTRAINT [PK_Students]
PRIMARY KEY CLUSTERED ([ID] ASC),
CONSTRAINT [FK_Students_Classrooms]
FOREIGN KEY ([SystemAccount_ID], [Classroom_ID])
REFERENCES [dbo].[Classrooms] ([SystemAccount_ID], [ID]),
CONSTRAINT [FK_Students_SystemAccounts] -- this wouldn't be needed if
FOREIGN KEY ([SystemAccount_ID]) -- Classrooms_ID was NOT NULL
REFERENCES [dbo].[SystemAccounts] ([ID])
);

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