Couple foreignKey reference a table with couple PrimaryKey - sql-server

I have two tables
CREATE TABLE [dbo].[Customer]
(
[SourceID] [int] NOT NULL,
[ID_N] [bigint] NOT NULL,
[RegionCode] [varchar](1) NOT NULL,
[NSID] [int] NOT NULL,
CONSTRAINT [Pk_Customer] PRIMARY KEY CLUSTERED
([RegionCode] ASC, [ID_N] ASC)
)
CREATE TABLE [dbo].[Order]
(
[Reference][nvarchar](50) NOT NULL,
[SourceID] [int] NOT NULL,
[ID_N] [nvarchar](50) NULL,
[RegionCode] [varchar](1) NULL,
[Customer_ID_N] [bigint] NULL,
CONSTRAINT [PK_Order] PRIMARY KEY CLUSTERED
([Reference] ASC)
)
I want to put (CustomemrID_N,RegionCode) as a Foreign Key reference to the Customer table.
Alter table [dbo].[Order]
ADD CONSTRAINT FK_Order_Customer FOREIGN KEY (Customer_ID_N,RegionCode)
REFERENCES[dbo].[Customer](ID_N,RegionCode)
but i get this error :
There are no primary or candidate keys in the referenced table 'dbo.Customer' that match the referencing column list in the foreign key 'FK_Order_Customer'.

There are so many problems with your attempt... Most are typographical.
Firstly this statement:
CREATE TABLE [dbo].[Customer](
[SourceID] [int] NOT NULL,
[ID_N] [bigint] NOT NULL,
[RegionCode] [varchar](1) NOT NULL,
[NSID] [int] NOT NULL,
CONSTRAINT [Pk_Customer] PRIMARY KEY CLUSTERED
([RegionCode] ASC, [ID_N] ASC)
This is missing a right parenthesis ()) at the end of the statement.
Then the next statement:
CREATE TABLE [dbo].[Order](
[Reference][nvarchar](50) NOT NULL,
[SourceID] [int] NOT NULL,
[ID_N] [nvarchar](50) NULL,
[RegionCode] [varchar](1) NULL,
[Customer_ID_N] [bigint] NULL,
CONSTRAINT [PK_Order] PRIMARY KEY CLUSTERED
([Reference] ASC)
This too, isn't valid, there is also a missing right parenthesis.
Your last statement is also, not valid:
Alter table [dbo].[Order]
ADD CONSTRAINT FK_Order_CustomerFOREIGN KEY ([Customer_ID_N],RegionCode)
REFERENCES[dbo].[Customer](ID_N,RegionCode)
CONSTRAINT FK_Order_CustomerFOREIGN KEY should be CONSTRAINT FK_Order_Customer FOREIGN KEY; notice the space between FK_Order_Customer and `FOREIGN.
Once we fix that we get yet something like this:
CREATE TABLE [dbo].[Customer](
[SourceID] [int] NOT NULL,
[ID_N] [bigint] NOT NULL,
[RegionCode] [varchar](1) NOT NULL,
[NSID] [int] NOT NULL,
CONSTRAINT [Pk_Customer] PRIMARY KEY CLUSTERED
([RegionCode] ASC, [ID_N] ASC))
GO
CREATE TABLE [dbo].[Order](
[Reference][nvarchar](50) NOT NULL,
[SourceID] [int] NOT NULL,
[ID_N] [nvarchar](50) NULL,
[RegionCode] [varchar](1) NULL,
[Customer_ID_N] [bigint] NULL,
CONSTRAINT [PK_Order] PRIMARY KEY CLUSTERED
([Reference] ASC))
GO
Alter table [dbo].[Order]
ADD CONSTRAINT FK_Order_Customer FOREIGN KEY ([Customer_ID_N],RegionCode)
REFERENCES[dbo].[Customer](ID_N,RegionCode)
Note, when you run that, you get the error you have above. That's because your PK is defined as [RegionCode] ASC, [ID_N] ASC not ID_N,RegionCode. So let's fix that as swap the foreign key around...
Alter table [dbo].[Order]
ADD CONSTRAINT FK_Order_Customer FOREIGN KEY (RegionCode,[Customer_ID_N])
REFERENCES[dbo].[Customer](RegionCode, ID_N)
And now it works.
Address the typographical errors, then read the error; it was telling you the problem.

Related

SQL Server, one table with data -> insert into table with a foreign key, and that foreign key table has to be filled also

For a school project I have made a .csv import via C# and imported all the data from the file into a table containing only strings. We have to do some validation on the imported code using SQL server which I have already done. The table I have imported my data into looks like this:
CREATE TABLE [dbo].[StoreData]
(
[StoreName] [nvarchar](max) NULL,
[Street] [nvarchar](max) NULL,
[StreetNumber] [nvarchar](max) NULL,
[City] [nvarchar](max) NULL,
[ZipCode] [nvarchar](max) NULL,
[TelephoneNumber] [nvarchar](max) NULL,
[Country] [nvarchar](max) NULL
)
With this table filled, I have to Insert this data into the [Stores] table :
CREATE TABLE [dbo].[Stores]
(
[Id] [nvarchar](450) NOT NULL, <- GUID
[Name] [nvarchar](85) NOT NULL,
[CountryCode] [nvarchar](max) NOT NULL,
[AddressId] [nvarchar](450) NULL <- FK to [Address] Table
)
And here is my problem, the [Stores] contains a FK to the [Addresses] table:
CREATE TABLE [dbo].[Addresses]
(
[Id] [nvarchar](450) NOT NULL, <- GUID
[Street] [nvarchar](100) NOT NULL,
[HouseNumber] [nvarchar](4) NOT NULL,
[Addition] [nvarchar](10) NULL,
[ZipCode] [nvarchar](6) NOT NULL,
[City] [nvarchar](85) NOT NULL,
[SeriesIndicationStart] [int] NOT NULL,
[SeriesIndicationEnd] [int] NOT NULL
CONSTRAINT [PK_Addresses] PRIMARY KEY CLUSTERED
)
So now I have [StoreData] that contains the data I have to put in [Addresses] and in [Stores], and I have to keep in mind that the FK has to be set in [Stores]. This is our first database semester, and I am clueless, and tomorrow is the deadline..
I hope someone can help me out.. thanks in advance!

'Employees' does not contain an identity column

I am trying to reseed my table column but getting error
'Employees' does not contain an identity column
I have checked my table and it does have an ID column.
DDL
CREATE TABLE [dbo].[Employees]
(
[ID] [int] NOT NULL,
[FirstName] [nvarchar](max) NULL,
[MiddleName] [nvarchar](max) NULL,
[LastName] [nvarchar](max) NULL,
[Email] [nvarchar](max) NULL,
CONSTRAINT [PK_Employees]
PRIMARY KEY CLUSTERED ([ID] ASC)
)
You need to specify the column as the IDENTITY column, it is not assumed/implicit.
CREATE TABLE [dbo].[Employees]
([ID] [int] IDENTITY(1,1) NOT NULL,
-- rest of columns

Display corresponding name based on ID SQL select query

I have 2 tables
tbl_jobs
CREATE TABLE [dbo].[tbl_jobs]
(
[JobID] [int] IDENTITY(1,1) NOT NULL,
[JobType] [nvarchar](50) NOT NULL,
[RequestID] [int] NOT NULL,
[AssignTo] [int] NOT NULL,
[FromOrgID] [int] NOT NULL,
[ToOrgID] [int] NOT NULL,
[Ammount] [nvarchar](50) NOT NULL,
[JobStatus] [nvarchar](50) NOT NULL,
[Remark] [nvarchar](50) NULL,
[strOwner] [nvarchar](50) NOT NULL,
[dbTstamp] [datetime2](7) NOT NULL,
CONSTRAINT [PK_tbl_jobs]
PRIMARY KEY CLUSTERED ([JobID] ASC)
) ON [PRIMARY]
GO
ALTER TABLE [dbo].[tbl_jobs] WITH CHECK
ADD CONSTRAINT [FK_tbl_jobs_tbl_orgs]
FOREIGN KEY([FromOrgID]) REFERENCES [dbo].[tbl_orgs] ([OrgID])
GO
ALTER TABLE [dbo].[tbl_jobs] CHECK CONSTRAINT [FK_tbl_jobs_tbl_orgs]
GO
ALTER TABLE [dbo].[tbl_jobs] WITH CHECK
ADD CONSTRAINT [FK_tbl_jobs_tbl_orgs1]
FOREIGN KEY([ToOrgID]) REFERENCES [dbo].[tbl_orgs] ([OrgID])
GO
tbl_orgs
CREATE TABLE [dbo].[tbl_orgs]
(
[OrgID] [int] IDENTITY(1,1) NOT NULL,
[OrgName] [nvarchar](50) NOT NULL,
[OrgTele] [nvarchar](50) NULL,
[OrgEmail] [nvarchar](50) NULL,
[OrgArea] [nvarchar](50) NOT NULL,
[OrgCity] [nvarchar](50) NOT NULL,
[OrgLocation] [nvarchar](50) NOT NULL,
[OrgType] [nvarchar](50) NOT NULL,
[OrgStatus] [nvarchar](50) NOT NULL,
[strOwner] [nvarchar](50) NOT NULL,
[dbTStamp] [datetime2](7) NOT NULL,
CONSTRAINT [PK_tbl_orgs]
PRIMARY KEY CLUSTERED ([OrgID] ASC)
) ON [PRIMARY]
GO
I need to get most of the tbl_jobs columns and corresponding tbl_orgs.OrgName for tbl_jobs.FromOrgID & tbl_jobs.ToOrgID.
If I choose tbl_orgs.orgname, I don't get the proper results.
I am stuck here. What type of query should I use to get the result.?
You're joining two times to the same table instance. You should click on "add table" and add tbl_orgs one more time and join "FromOrgID" to one instance of it and "ToOrgID" to the other one. Otherwise the join doesn't make sense unless "FromOrgID" and "ToOrgID" are equal.

Billing Database

I have created 2 tables # CustomerHistory and # CustomerPaymentHistory
here is the sql syntax
CREATE TABLE [dbo].[CustomerHistory]
(
[ID] INT IDENTITY (1, 1) NOT NULL,
[HistoryID] AS ('CLI'+right('000000000'+CONVERT([varchar](10),[ID]),(5))) PERSISTED NOT NULL,
[CustomerID] INT NOT NULL,
[InvoiceNumber] NVARCHAR(30) NOT NULL,
[InvoiceDate] DATETIME NOT NULL,
[InvoiceTotal] NVARCHAR(20) NOT NULL,
[Balance] NVARCHAR(20) NOT NULL,
CONSTRAINT [PK_CUSTOMERHISTORY]
PRIMARY KEY CLUSTERED ([ID] ASC, [CustomerID] ASC),
CONSTRAINT [FK_CUSTOMER_CH]
FOREIGN KEY ([CustomerID]) REFERENCES [dbo].[Customers] ([ID])
)
and
CREATE TABLE [dbo].[CustomerPaymentHistory]
(
[ID] INT IDENTITY (1, 1) NOT NULL,
[PaymentID] AS ('CLI'+right('000000000'+CONVERT([varchar](10),[ID]),(5))) PERSISTED NOT NULL,
[HistoryID] INT NOT NULL,
[PaymentDate] DATETIME NOT NULL,
[PaymentAmount] NVARCHAR(20) NOT NULL,
[BalanceDue] NVARCHAR(20) NULL,
[PaidInFull] BIT NOT NULL,
CONSTRAINT [PK_CUSTOMERPAYMENTHISTORY]
PRIMARY KEY CLUSTERED ([ID] ASC, [HistoryID] ASC),
CONSTRAINT [FK_CUSTOMERHISTORY_CPH]
FOREIGN KEY ([HistoryID]) REFERENCES [dbo].[CustomerHistory] ([ID])
)
but when i'm trying to update the table, I get an error:
Update cannot proceed due to validation errors.
Please correct the following errors and try again.
SQL71516 :: The referenced table '[dbo].[CustomerHistory]' 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 can fix this problem?

deleting an employee conflicts with department manager foreign key constraint

I created two tables , departments and employees with the following structure :
CREATE TABLE [dbo].[departments](
[department_id] [bigint] IDENTITY(10,10) NOT NULL,
[department_name] [nvarchar](30) NOT NULL,
[manager_id] [bigint] NULL,
[location_id] [bigint] NULL,
[department_notes] [varchar](150) NULL,
[created_by] [bigint] NULL,
[created_date] [datetime] NULL,
[last_updated_by] [bigint] NULL,
[last_updated_date1] [datetime] NULL,
[status] [varchar](12) NOT NULL,
CONSTRAINT [PK_departments] PRIMARY KEY CLUSTERED
(
[department_id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY],
CONSTRAINT [UQ_NoRepeat] UNIQUE NONCLUSTERED
(
[department_name] ASC,
[location_id] ASC,
[status] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
ALTER TABLE [dbo].[departments] ADD CONSTRAINT [DF_departments_created_date] DEFAULT (getdate()) FOR [created_date]
GO
ALTER TABLE [dbo].[departments] ADD CONSTRAINT [DF_departments_created_date1] DEFAULT (getdate()) FOR [last_updated_date1]
GO
ALTER TABLE [dbo].[departments] ADD CONSTRAINT [DF_departments_status] DEFAULT ('Active') FOR [status]
GO
ALTER TABLE [dbo].[departments] WITH CHECK ADD FOREIGN KEY([manager_id])
REFERENCES [dbo].[employees] ([employee_id])
GO
ALTER TABLE [dbo].[departments] WITH CHECK ADD CONSTRAINT [FK_departments_locations] FOREIGN KEY([location_id])
REFERENCES [dbo].[locations] ([location_id])
GO
ALTER TABLE [dbo].[departments] CHECK CONSTRAINT [FK_departments_locations]
GO
ALTER TABLE [dbo].[departments] WITH CHECK ADD CONSTRAINT [Ck_deptStatus] CHECK (([Status]='Deleted' OR [Status]='Active'))
GO
ALTER TABLE [dbo].[departments] CHECK CONSTRAINT [Ck_deptStatus]
GO
CREATE TABLE [dbo].[employees](
[employee_id] [bigint] NOT NULL,
[first_name] [nvarchar](20) NULL,
[last_name] [nvarchar](25) NOT NULL,
[email] [nvarchar](25) NOT NULL,
[phone_number] [nvarchar](20) NULL,
[hire_date] [date] NULL,
[job_id] [nvarchar](10) NOT NULL,
[salary] [numeric](8, 2) NOT NULL,
[commission_pct] [numeric](2, 2) NULL,
[manager_id] [bigint] NULL,
[department_id] [bigint] NOT NULL,
[allow_login] [bit] NOT NULL,
[user_id] [nvarchar](128) NULL,
[allow_email] [bit] NOT NULL,
[driv_lic_no] [nchar](20) NULL,
[reporting_to] [bigint] NULL,
[salutation] [nchar](10) NULL,
[date_of_birth] [date] NULL,
[gender] [nchar](10) NULL,
[blood_group] [nchar](10) NULL,
[Nationality] [nchar](10) NULL,
[gov_id] [nchar](25) NULL,
[passport_no] [nchar](25) NULL,
[passport_expir] [date] NULL,
[driv_lic_expir] [date] NULL,
[perm_address] [varchar](250) NULL,
[perm_city] [varchar](50) NULL,
[perm_state] [varchar](50) NULL,
[per_zip] [nchar](20) NULL,
[perm_country] [nvarchar](6) NULL,
[current_address] [varchar](250) NULL,
[current_city] [varchar](50) NULL,
[current_state] [varchar](50) NULL,
[current_zip] [nchar](20) NULL,
[current_country] [nvarchar](6) NULL,
[mobile_no] [nvarchar](20) NULL,
[notes] [varchar](250) NULL,
[added_by] [bigint] NULL,
[added_on] [date] NULL,
[send_cred_by_email] [bit] NOT NULL,
[user_name] [nvarchar](256) NULL,
CONSTRAINT [PK_employees] PRIMARY KEY CLUSTERED
(
[employee_id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
ALTER TABLE [dbo].[employees] ADD CONSTRAINT [DF_employees_allow_login] DEFAULT ((0)) FOR [allow_login]
GO
ALTER TABLE [dbo].[employees] ADD CONSTRAINT [DF_employees_allow_email] DEFAULT ((0)) FOR [allow_email]
GO
ALTER TABLE [dbo].[employees] ADD DEFAULT ('Mr.') FOR [salutation]
GO
ALTER TABLE [dbo].[employees] ADD DEFAULT ((1)) FOR [send_cred_by_email]
GO
ALTER TABLE [dbo].[employees] WITH CHECK ADD CONSTRAINT [FK_employees_AspNetUsers] FOREIGN KEY([user_id])
REFERENCES [dbo].[AspNetUsers] ([Id])
GO
ALTER TABLE [dbo].[employees] CHECK CONSTRAINT [FK_employees_AspNetUsers]
GO
ALTER TABLE [dbo].[employees] WITH CHECK ADD CONSTRAINT [FK_employees_countries] FOREIGN KEY([perm_country])
REFERENCES [dbo].[countries] ([country_id])
GO
ALTER TABLE [dbo].[employees] CHECK CONSTRAINT [FK_employees_countries]
GO
ALTER TABLE [dbo].[employees] WITH CHECK ADD CONSTRAINT [FK_employees_countries1] FOREIGN KEY([current_country])
REFERENCES [dbo].[countries] ([country_id])
GO
ALTER TABLE [dbo].[employees] CHECK CONSTRAINT [FK_employees_countries1]
GO
ALTER TABLE [dbo].[employees] WITH CHECK ADD CONSTRAINT [FK_employees_employees] FOREIGN KEY([employee_id])
REFERENCES [dbo].[employees] ([employee_id])
GO
ALTER TABLE [dbo].[employees] CHECK CONSTRAINT [FK_employees_employees]
GO
there were some existing employees which are already managers in departments table , now when I try to delete any of those manager employees, I get a foreign key constraint conflict error blocking the delete statement.
what is the problem please ?
The problem is that you're not allowed to do that.
A foreign key constraint is an integrity constraint meaning that it ensures data integrity across tables.
If one department row says that the ID of the employee that is the manager of this department is 73, it would not be good if there is no employee in the database with an ID of 73.
A foreign key constraint ensures this won't happen:
You cannot insert or update a department row to have a manager id that does not exist in the employee table
You cannot delete an employee that is referenced as a manager from a department row
You cannot update the ID of an employee that is referenced as a manager from a department row
The solution is to first fix the department by:
Switching to a different manager by updating the department row and adjusting the ID of the manager
NULL'ing out the manager, saying that this department has no manager, if that is allowed
After doing any of those two actions you should be able to delete the employee, assuming there's no other foreign key references as well.

Resources