Cannot insert duplicate key row in object 'dbo.CFD' with unique index - sql-server

I am running into an error on the insertion of a single row into a table, dbo.CFD. The complete error states:
Cannot insert duplicate key row in object 'dbo.CFD' with unique index 'IX_CFD_NRSC_FXTR_N'. The duplicate key value is (BP2001, 1990, CHK, 01, 3456).
Looking at the index in question, IX_CFD_NRSC_FXTR_N, it is a non-unique, non-clustered index on a single column (The column with BP2001 in the error).
Looking at the data, there are many records with the values of BP2001, CHK, 01, and 3456, however none with 1990 (but various other values), so it doesn't seem I am conflicting with a unique constraint.
I also verified that all foreign key constraints are being met and the primary key constraint is not being violated.
How can I figure out what exactly is causing this issue? Every example I can find results in there being duplicate data being inserted, but I don't think that is the issue here. Thanks!
Edit----------
The table create script:
CREATE TABLE [dbo].[CFD](
[PRPSL_I] [int] NOT NULL,
[FILE_TYPE_C] [char](3) NOT NULL,
[CAD_FLR_C] [char](2) NOT NULL,
[FXTR_SERL_I] [int] NOT NULL,
[ADJC_I] [int] NULL,
[CMP_I] [int] NULL,
[VER_I] [int] NULL,
[NRSC_FXTR_N] [varchar](15) NULL,
[MDSE_SPCE_HT_I] [int] NULL,
[MDSE_SPCE_LGTH_I] [int] NULL,
[MDSE_SPCE_DPT_I] [int] NULL,
[NRSC_FXTR_SIDE_I] [int] NULL,
[NRSC_FXTR_SECT_I] [int] NULL,
[BOFM_INCL_F] [bit] NOT NULL,
[DIVI_I] [int] NULL,
[PRTY_I] [int] NULL,
[REUSE_I] [int] NULL,
[FXTR_ISTL_LOC_N] [varchar](6) NULL,
[PHYS_SECT_NUM_I] [int] NULL,
[SAFL_LOC_N] [varchar](4) NULL,
[SEQ_I] [int] NULL,
[SIDE_ASLE_I] [int] NULL,
[LDIN_I] [int] NULL,
[LDIN_STAT_I] [int] NULL,
CONSTRAINT [PK_CFD] PRIMARY KEY CLUSTERED
(
[PRPSL_I] ASC,
[FILE_TYPE_C] ASC,
[CAD_FLR_C] ASC,
[FXTR_SERL_I] ASC
)WITH (PAD_INDEX = ON, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 80) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
ALTER TABLE [dbo].[CFD] ADD CONSTRAINT [DF_CFD_BOFM_INCL_F] DEFAULT ((0)) FOR [BOFM_INCL_F]
GO
ALTER TABLE [dbo].[CFD] WITH CHECK ADD CONSTRAINT [FK1_CFD] FOREIGN KEY([PRPSL_I], [FILE_TYPE_C], [CAD_FLR_C])
REFERENCES [dbo].[CAD_FILE] ([PRPSL_I], [FILE_TYPE_C], [CAD_FLR_C])
GO
ALTER TABLE [dbo].[CFD] CHECK CONSTRAINT [FK1_CFD]
GO
ALTER TABLE [dbo].[CFD] WITH CHECK ADD CONSTRAINT [FK2_CFD] FOREIGN KEY([CMP_I])
REFERENCES [dbo].[CMP] ([CMP_I])
GO
ALTER TABLE [dbo].[CFD] CHECK CONSTRAINT [FK2_CFD]
GO
ALTER TABLE [dbo].[CFD] WITH CHECK ADD CONSTRAINT [FK3_CFD] FOREIGN KEY([ADJC_I])
REFERENCES [dbo].[ADJC_E] ([ADJC_I])
GO
ALTER TABLE [dbo].[CFD] CHECK CONSTRAINT [FK3_CFD]
GO
ALTER TABLE [dbo].[CFD] WITH CHECK ADD CONSTRAINT [CK_CFD] CHECK (([FILE_TYPE_C]<>'SFP'))
GO
ALTER TABLE [dbo].[CFD] CHECK CONSTRAINT [CK_CFD]
GO
CREATE NONCLUSTERED INDEX [IX_CFD_NRSC_FXTR_N] ON [dbo].[CFD]
(
[NRSC_FXTR_N] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
GO

Related

Group by In SQL query is not working well in my query

I have 3 tables . Orders, OrderLines, BillLines. The primary key of Orders is a FK in the 2 other tables.
I am trying to query the client debit and credit amount.
The Action table just describe the type of the transaction
The Subindex table stores the clients names and ids
CREATE TABLE [dbo].[Orders](
[OrderID] [int] IDENTITY(1,1) NOT NULL,
[Ordertype] [nvarchar](max) NULL,
[Orderdate] [datetime2](7) NOT NULL,
[transactionNo] [int] NOT NULL,
[DocumentNo] [int] NOT NULL,
[ordernote] [nvarchar](max) NULL,
[Profittax] [decimal](18, 2) NOT NULL,
[DescDR] [decimal](18, 2) NULL,
[DescCR] [decimal](18, 2) NULL,
[ActionsID] [smallint] NOT NULL,
[SubIndexesID] [smallint] NULL,
CONSTRAINT [PK_dbo.Orders] PRIMARY KEY CLUSTERED
(
[OrderID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO
ALTER TABLE [dbo].[Orders] WITH CHECK ADD CONSTRAINT [FK_dbo.Orders_dbo.Actions_ActionsID] FOREIGN KEY([ActionsID])
REFERENCES [dbo].[Actions] ([ActionsID])
ON DELETE CASCADE
GO
ALTER TABLE [dbo].[Orders] CHECK CONSTRAINT [FK_dbo.Orders_dbo.Actions_ActionsID]
GO
ALTER TABLE [dbo].[Orders] WITH CHECK ADD CONSTRAINT [FK_dbo.Orders_dbo.SubIndexes_SubIndexesID] FOREIGN KEY([SubIndexesID])
REFERENCES [dbo].[SubIndexes] ([SubIndexesID])
GO
ALTER TABLE [dbo].[Orders] CHECK CONSTRAINT [FK_dbo.Orders_dbo.SubIndexes_SubIndexesID]
GO
CREATE TABLE [dbo].[Orderlines](
[OrderlinesID] [int] IDENTITY(1,1) NOT NULL,
[OrderID] [int] NOT NULL,
[Qin] [smallint] NOT NULL,
[Qout] [smallint] NOT NULL,
[Price] [decimal](18, 2) NOT NULL,
[currency] [nvarchar](max) NULL,
[Discount] [decimal](18, 2) NOT NULL,
[VAT] [decimal](18, 2) NOT NULL,
[ItemsID] [smallint] NOT NULL,
[Total] [decimal](18, 2) NOT NULL,
[Vatvalue] [decimal](18, 2) NOT NULL,
[Net] [decimal](18, 2) NOT NULL,
CONSTRAINT [PK_dbo.Orderlines] PRIMARY KEY CLUSTERED
(
[OrderlinesID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO
ALTER TABLE [dbo].[Orderlines] ADD DEFAULT ((0)) FOR [Total]
GO
ALTER TABLE [dbo].[Orderlines] ADD DEFAULT ((0)) FOR [Vatvalue]
GO
ALTER TABLE [dbo].[Orderlines] ADD DEFAULT ((0)) FOR [Net]
GO
ALTER TABLE [dbo].[Orderlines] WITH CHECK ADD CONSTRAINT [FK_dbo.Orderlines_dbo.Items_ItemsID] FOREIGN KEY([ItemsID])
REFERENCES [dbo].[Items] ([ItemsID])
ON DELETE CASCADE
GO
ALTER TABLE [dbo].[Orderlines] CHECK CONSTRAINT [FK_dbo.Orderlines_dbo.Items_ItemsID]
GO
ALTER TABLE [dbo].[Orderlines] WITH CHECK ADD CONSTRAINT [FK_dbo.Orderlines_dbo.Orders_OrderID] FOREIGN KEY([OrderID])
REFERENCES [dbo].[Orders] ([OrderID])
ON DELETE CASCADE
GO
ALTER TABLE [dbo].[Orderlines] CHECK CONSTRAINT [FK_dbo.Orderlines_dbo.Orders_OrderID]
GO
CREATE TABLE [dbo].[BillLines](
[BillLinesID] [int] IDENTITY(1,1) NOT NULL,
[VALIN] [decimal](18, 2) NULL,
[VALOut] [decimal](18, 2) NULL,
[OrderID] [int] NOT NULL,
[SubIndexesID] [smallint] NULL,
CONSTRAINT [PK_dbo.BillLines] PRIMARY KEY CLUSTERED
(
[BillLinesID] 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
ALTER TABLE [dbo].[BillLines] WITH CHECK ADD CONSTRAINT [FK_dbo.BillLines_dbo.Orders_OrderID] FOREIGN KEY([OrderID])
REFERENCES [dbo].[Orders] ([OrderID])
ON DELETE CASCADE
GO
ALTER TABLE [dbo].[BillLines] CHECK CONSTRAINT [FK_dbo.BillLines_dbo.Orders_OrderID]
GO
ALTER TABLE [dbo].[BillLines] WITH CHECK ADD CONSTRAINT [FK_dbo.BillLines_dbo.SubIndexes_SubIndexesID] FOREIGN KEY([SubIndexesID])
REFERENCES [dbo].[SubIndexes] ([SubIndexesID])
GO
ALTER TABLE [dbo].[BillLines] CHECK CONSTRAINT [FK_dbo.BillLines_dbo.SubIndexes_SubIndexesID]
GO
CREATE TABLE [dbo].[Actions](
[ActionsID] [smallint] IDENTITY(1,1) NOT NULL,
[Actionname] [nvarchar](4000) NOT NULL,
CONSTRAINT [PK_dbo.Actions] PRIMARY KEY CLUSTERED
(
[ActionsID] 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
CREATE TABLE [dbo].[SubIndexes](
[SubIndexesID] [smallint] IDENTITY(1,1) NOT NULL,
[Subname] [nvarchar](max) NULL,
[AccountIndexID] [smallint] NOT NULL,
[Contacttype] [nvarchar](max) NULL,
[phones] [nvarchar](max) NULL,
[fax] [nvarchar](max) NULL,
[email] [nvarchar](max) NULL,
[address] [nvarchar](max) NULL,
[zip] [nvarchar](max) NULL,
[Website] [nvarchar](max) NULL,
CONSTRAINT [PK_dbo.SubIndexes] PRIMARY KEY CLUSTERED
(
[SubIndexesID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO
ALTER TABLE [dbo].[SubIndexes] WITH CHECK ADD CONSTRAINT [FK_dbo.SubIndexes_dbo.AccountIndexes_AccountIndexID] FOREIGN KEY([AccountIndexID])
REFERENCES [dbo].[AccountIndexes] ([AccountIndexID])
ON DELETE CASCADE
GO
ALTER TABLE [dbo].[SubIndexes] CHECK CONSTRAINT [FK_dbo.SubIndexes_dbo.AccountIndexes_AccountIndexID]
GO
My Query is
select distinct
o.OrderID ,
s.Subname as subindexname,
o.SubIndexesID as Subindex ,
sum(ol.Qout * (ol.Price - ol.Discount)* (1+(ol.VAT/100)-(o.Profittax/100))+ bl.VALOut) -iif(o.ActionsID between 3 and 4, o.DescDR+o.DescCR,0) as Debit ,
sum(ol.Qin * (ol.Price - ol.Discount )* (1+(ol.VAT/100)-(o.Profittax/100))+ bl.VALIN)-iif(o.ActionsID not between 3 and 4,o.DescCR + o.DescDR,0) as Credit
from Orders o
inner join
Orderlines ol on o.OrderID = ol.OrderID
inner join
BillLines bl on o.OrderID = bl.OrderID
inner join
SubIndexes s on o.SubIndexesID= s.SubIndexesID
group by o.OrderID,
o.ActionsID,
o.SubIndexesID,
o.DescCR,
o.DescDR,
ol.Qout,
ol.Qin,
s.Subname,
s.SubIndexesID,
ol.VAT,
ol.Price,
ol.Discount
having o.ActionsID=2
or o.ActionsID=3
or o.ActionsID=4
or o.ActionsID=5
I want to show the debit and the credit in one row even I have multiple orderlines for one order.
It is necessary to include all cols in Group-by in Select as well:
select distinct
o.OrderID ,
s.Subname as subindexname,
o.SubIndexesID as Subindex ,
o.ActionsID,
o.DescCR,
o.DescDR,
ol.Qout,
ol.Qin,
s.Subname,
s.SubIndexesID,
ol.VAT,
ol.Price,
ol.Discount
sum(ol.Qout * (ol.Price - ol.Discount)* (1+(ol.VAT/100)-(o.Profittax/100))+ bl.VALOut) -iif(o.ActionsID between 3 and 4, o.DescDR+o.DescCR,0) as Debit ,
sum(ol.Qin * (ol.Price - ol.Discount )* (1+(ol.VAT/100)-(o.Profittax/100))+ bl.VALIN)-iif(o.ActionsID not between 3 and 4,o.DescCR + o.DescDR,0) as Credit
from Orders o
inner join
Orderlines ol on o.OrderID = ol.OrderID
inner join
BillLines bl on o.OrderID = bl.OrderID
inner join
SubIndexes s on o.SubIndexesID= s.SubIndexesID
group by o.OrderID,
o.ActionsID,
o.SubIndexesID,
o.DescCR,
o.DescDR,
ol.Qout,
ol.Qin,
s.Subname,
s.SubIndexesID,
ol.VAT,
ol.Price,
ol.Discount
having o.ActionsID=2
or o.ActionsID=3
or o.ActionsID=4
or o.ActionsID=5

There are no primary or candidate keys in the referenced table in sql server 2008

ClassCode Table
CREATE TABLE [dbo].[ClassCode](
[SchoolCode] [nvarchar](10) NOT NULL,
[ClassCode] [nvarchar](4) NOT NULL,
[ClassName] [nvarchar](50) NOT NULL,
[ClassRange] [int] NOT NULL,
[ClassDuration] numeric(38,2) NOT NULL,
[UserID] [nvarchar](30) NULL,
[RecordDate] [smalldatetime] NULL,
CONSTRAINT [PK_ClassCode] PRIMARY KEY CLUSTERED
(
[SchoolCode] ASC,
[ClassCode] ASC,
[ClassRange]
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
ExamDeclaration Table
CREATE TABLE [dbo].[ExamDeclaration](
[SchoolCode] [nvarchar](10) NOT NULL,
[ClassCode] [nvarchar](4) NOT NULL,
[ExamCode] [nvarchar](4) NOT NULL,
[RegistationFess] numeric(38,2) NOT NULL,
[RegistatinStartDate] [date] NOT NULL,
[RegistatinEndDate] [date] NOT NULL,
[ExamStartDate] [date] NOT NULL,
[UserID] [nvarchar](30) NULL,
[RecordDate] [smalldatetime] NULL
CONSTRAINT [PK_ExamDeclaration] PRIMARY KEY CLUSTERED
(
[SchoolCode] ASC,
[ClassCode] ASC,
[ExamCode] 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
ALTER TABLE [dbo].[ExamDeclaration] WITH CHECK ADD CONSTRAINT [FK_ExamDeclaration_ClassCode] FOREIGN KEY([ClassCode])
REFERENCES [dbo].[ClassCode] ([ClassCode])
GO
ALTER TABLE [dbo].[ExamDeclaration] CHECK CONSTRAINT [FK_ExamDeclaration_ClassCode]
GO
I am trying to set Foreign key ClassCode
but got this error
Msg 1776, Level 16, State 0, Line 2 There are no primary or candidate
keys in the referenced table 'dbo.ClassCode' that match the
referencing column list in the foreign key
'FK_ExamDeclaration_ClassCode'. Msg 1750, Level 16, State 0, Line 2
Could not create constraint. See previous errors. Msg 4917, Level 16,
State 0, Line 2 Constraint 'FK_ExamDeclaration_ClassCode' does not
exist. Msg 4916, Level 16, State 0, Line 2 Could not enable or disable
the constraint. See previous errors.
What is the problem in these two tables?
thank you..
Your foreign key must match exactly the primary key!
If you declare the primary key like this PK(X int,Y int, Z int), then the FK must be declared like this: FK (a int, b int, c int) references MyTable(X,Y,Z).
In your case, your Pk is (SchoolCode, ClassCode, ClassRange). This means you should declare FK like this:
ALTER TABLE [dbo].[ExamDeclaration] WITH CHECK ADD CONSTRAINT [FK_ExamDeclaration_ClassCode] FOREIGN KEY(SchoolCode, ClassCode, ClassRange)
REFERENCES [dbo].[ClassCode] (SchoolCode, ClassCode, ClassRange)
GO
Modify your table ExamDeclaration, add column 'ClassRange'.

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.

An IF inside a check constraint SQL

I have this table..
CREATE TABLE [dbo].[Tipo_Servicios_Info](
[TSI_TS_Id] [int] NOT NULL,
[TS_Tar_Id] [int] NOT NULL,
[TS_PDI_Id] [int] NOT NULL,
[TSI_Descripcion] varchar(100),
[TSI_FechaIni] date not null,
[TSI_FechaFin] date not null,
[TSI_HoraMin] time,
[TSI_HoraMax] time,
[TSI_Duracion] varchar(50) not null,
[TSI_Unidad] varchar(50) not null,
[TSI_Cantidad] int not null,
CONSTRAINT [PK_TIPO_SERVICIOS_INFO] PRIMARY KEY CLUSTERED
(
[TSI_TS_Id] ASC,
[TS_Tar_Id] ASC,
[TS_PDI_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
With some checks..
ALTER TABLE Dbo.Tipo_Servicios_Info
ADD CONSTRAINT Ck_Valores_Unidad CHECK(Tsi_Unidad IN('Dia', 'Hora'));
GO
ALTER TABLE Dbo.Tipo_Servicios_Info
ADD CONSTRAINT Df_Tipo_Servicios_Info_Tsi_Unidad DEFAULT 'Dia' FOR Tsi_Unidad;
GO
In this two above I set as default value of the TSI_Unidad to 'Dia', but this field only can contain Dia or Hora by the second constraint.
But i have a problem, I must define TSI_HoraMin and TSI_HoraMax that can be null(if TSI_Unidad is Dia, they have to be nullable), but if TSI_Unidad is Hora, [TSI_HoraMin] and [TSI_HoraMax] cant be null.
I want to create a new constraint but i dont know how can i do it..
This would be the idea..
ALTER TABLE [dbo].[Tipo_Servicios_Info]
ADD CONSTRAINT CK_HorasMin CHECK([TSI_HoraMin] is not null if [TSI_Unidad] = 'Hora')
GO
But this constraint, obviously, isnt well defined.
From what I gather you are trying to not allow a null value for TSI_HoraMin if TSI_Unidad = 'Hora`. In which case you could use:
ALTER TABLE [dbo].[Tipo_Servicios_Info]
ADD CONSTRAINT CK_HorasMin
CHECK(NOT([TSI_HoraMin] IS NULL AND [TSI_Unidad] = 'Hora'));

LINQ query issue: returning multiple records

I have 2 tables. Problem is I always get multiple records no matter what I do.
Pages
SubMenus
Relation is 1 to 1 (each submenu has a page)
SubMenus sample data:
submenu_id parentmenu_id display_name url_name
----------------------------------------------------
1 1 Home home
2 1 Contact contact
Pages table data:
page_id submenu_id page_title url_name
---------------------------------------------------------
1 1 Home Page home
2 1 Contact Page null
I want to retrieve single value from there JOIN where SubMenu.UrlName == Home
(from s in SubMenus
join p in Pages on s.Id equals p.SubMenuId
where s.UrlName == "home"
select new
{
s.Id, s.UrlName,
PageId = p.Id, p.Title, p.Html,
p.MetaAuthor, p.MetaKeywords, p.MetaDescription
}).FirstOrDefault();
But if I check the SQL and run it. I get single record without any problem. Below is what SQL generated
SELECT TOP (1)
[Extent1].[submenu_id] AS [submenu_id],
[Extent1].[url_name] AS [url_name],
[Extent2].[page_id] AS [page_id],
[Extent2].[page_title] AS [page_title],
[Extent2].[page_html] AS [page_html],
[Extent2].[meta_author] AS [meta_author],
[Extent2].[meta_keywords] AS [meta_keywords],
[Extent2].[meta_description] AS [meta_description]
FROM
[dbo].[SubMenu] AS [Extent1]
INNER JOIN
[dbo].[Pages] AS [Extent2] ON [Extent1].[submenu_id] = [Extent2].[submenu_id]
WHERE
N'home' = [Extent1].[url_name]
Table structure:
CREATE TABLE [dbo].[ParentMenu]
(
[parentmenu_id] [int] IDENTITY(1,1) NOT NULL,
[group_name] [nvarchar](50) NULL,
[title] [nvarchar](100) NULL,
[active] [bit] NOT NULL,
[index_order] [int] NULL,
CONSTRAINT [PK_ParentMenu]
PRIMARY KEY CLUSTERED ([parentmenu_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
ALTER TABLE [dbo].[ParentMenu]
ADD CONSTRAINT [DF_ParentMenu_active] DEFAULT ((1)) FOR [active]
GO
ALTER TABLE [dbo].[ParentMenu]
ADD CONSTRAINT [DF_ParentMenu_index_order] DEFAULT ((0)) FOR [index_order]
GO
CREATE TABLE [dbo].[SubMenu]
(
[submenu_id] [int] IDENTITY(1,1) NOT NULL,
[parentmenu_id] [int] NOT NULL,
[display_name] [nvarchar](100) NULL,
[url_name] [nvarchar](100) NULL,
[index_order] [int] NULL,
[active] [bit] NOT NULL,
CONSTRAINT [PK_SubMenu]
PRIMARY KEY CLUSTERED ([submenu_id] ASC)
WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF,
IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON,
ALLOW_PAGE_LOCKS = ON) ON [PRIMARY],
CONSTRAINT [IX_SubMenu_1]
UNIQUE NONCLUSTERED ([url_name] 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
ALTER TABLE [dbo].[SubMenu] WITH CHECK
ADD CONSTRAINT [FK_SubMenu_ParentMenu]
FOREIGN KEY([parentmenu_id]) REFERENCES [dbo].[ParentMenu] ([parentmenu_id])
ON DELETE CASCADE
GO
ALTER TABLE [dbo].[SubMenu] CHECK CONSTRAINT [FK_SubMenu_ParentMenu]
GO
ALTER TABLE [dbo].[SubMenu]
ADD CONSTRAINT [DF_SubMenu_index_order] DEFAULT ((0)) FOR [index_order]
GO
ALTER TABLE [dbo].[SubMenu]
ADD CONSTRAINT [DF_SubMenu_active] DEFAULT ((1)) FOR [active]
GO
CREATE TABLE [dbo].[Pages]
(
[page_id] [int] IDENTITY(1,1) NOT NULL,
[submenu_id] [int] NOT NULL,
[page_title] [nvarchar](200) NULL,
[url_name] [nvarchar](100) NULL,
[page_html] [nvarchar](max) NULL,
[meta_author] [nvarchar](300) NULL,
[meta_keywords] [nvarchar](max) NULL,
[meta_description] [nvarchar](max) NULL,
[active] [bit] NOT NULL,
[creation_date] [date] NULL,
CONSTRAINT [PK_Pages]
PRIMARY KEY CLUSTERED ([page_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
ALTER TABLE [dbo].[Pages] WITH CHECK
ADD CONSTRAINT [FK_Pages_SubMenu]
FOREIGN KEY([submenu_id]) REFERENCES [dbo].[SubMenu] ([submenu_id])
ON DELETE CASCADE
GO
ALTER TABLE [dbo].[Pages] CHECK CONSTRAINT [FK_Pages_SubMenu]
GO
ALTER TABLE [dbo].[Pages]
ADD CONSTRAINT [DF_Pages_active] DEFAULT ((1)) FOR [active]
GO
You are saying that Problem is I always get multiple records no matter what I do.
The query that you show has top 1 in the very first line, it will always return just one row.
What's wrong with it?
From what I see your SQL query matches what your LINQ query does.
In this case LINQ query cannot possible return more rows than SQL returns.

Resources