foreign key relationships on delete cascade on update cascade - sql

In sql server 2012 , I have table PurchaseReturn(VendorId,PurchaseOrderId). The column 'Vendorid' is a foreign key relationship to Vendor(VendorId) and 'Purchaseorderid' is to Purchaseorder(purchaseorderi).
Now my target is to set type of foreign key for 'VendorId' as 'On delete Set Null on Update Cascade' but For 'purchaseorderid' it should be 'On delete CasCade On Update Cascade'.
But when i have created FK for VendorId and trying to make it for PurchaseOrderId by following query:
alter table PurchaseReturn add constraint FK_PR_PORD foreign key (Purchaseorderid) references PurchaseOrder(Purchaseorderid) on delete cascade ON UPDATE CASCADE ';
an errors appears like this:
Introducing FOREIGN KEY constraint 'FK_PR_PORD' on table 'PurchaseReturn' may cause cycles or multiple cascade paths. Specify ON DELETE NO ACTION or ON UPDATE NO ACTION, or modify other FOREIGN KEY constraints.
What is the problem?... plz help thanks in advance
This is the create table query alonq with constraints
USE [AsifTraders]
GO
/****** Object: Table [dbo].[PurchaseReturn] Script Date: 24-Sep-14 11:46:39 AM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[PurchaseReturn](
[Date] [datetime] NOT NULL,
[PurchaseReturnId] [nvarchar](20) NOT NULL,
[VendorId] [nvarchar](8) NULL,
[Description] [nvarchar](50) NOT NULL,
[ReturnType] [nvarchar](20) NOT NULL,
[Deduction] [numeric](15, 0) NULL,
[ProductQuantity] [numeric](10, 2) NOT NULL,
[PurchaseValue] [numeric](12, 0) NOT NULL,
[ReturnValue] [numeric](15, 0) NOT NULL,
[Paid] [numeric](15, 0) NULL,
[PBalance] [numeric](15, 0) NULL,
[NBalance] [numeric](15, 0) NULL,
[JEntryId] [int] NOT NULL,
[PURCHASEORDERID] [nvarchar](8) NULL,
CONSTRAINT [PK_PurchaseReturn] PRIMARY KEY CLUSTERED
(
[PurchaseReturnId] 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].[PurchaseReturn] WITH CHECK ADD CONSTRAINT [FK_PR_VEN] FOREIGN KEY([PURCHASEORDERID])
REFERENCES [dbo].[PurchaseOrder] ([PurchaseOrderId])
ON UPDATE CASCADE
ON DELETE CASCADE
GO
ALTER TABLE [dbo].[PurchaseReturn] CHECK CONSTRAINT [FK_PR_VEN]
GO
This is the query for PurhcaseOrder
USE [AsifTraders]
GO
/****** Object: Table [dbo].[PurchaseOrder] Script Date: 24-Sep-14 11:56:53 AM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[PurchaseOrder](
[Date] [datetime] NULL,
[PurchaseOrderId] [nvarchar](8) NOT NULL,
[JEntryId] [int] NULL,
[VendorId] [nvarchar](8) NULL,
[PurchaseType] [nvarchar](10) NULL,
[Description] [nvarchar](50) NOT NULL,
[ItemQuantity] [numeric](18, 0) NOT NULL,
[DeleiveryCharges] [numeric](18, 0) NULL,
[Discount] [numeric](18, 0) NULL,
[Total] [numeric](18, 0) NOT NULL,
[Paid] [numeric](18, 0) NULL,
[PBalance] [numeric](18, 0) NULL,
[NBalance] [numeric](18, 0) NULL,
PRIMARY KEY CLUSTERED
(
[PurchaseOrderId] 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].[PurchaseOrder] WITH CHECK ADD CONSTRAINT [fk_purch_ven] FOREIGN KEY([VendorId])
REFERENCES [dbo].[Vendor] ([VendorId])
ON UPDATE CASCADE
ON DELETE CASCADE
GO
ALTER TABLE [dbo].[PurchaseOrder] CHECK CONSTRAINT [fk_purch_ven]
GO

Related

There are more than three data in one of the cells that are bit formats

I need to have Select up to 3 company Types in SQL and use check constrain.
How to do this, or I also accept other suggestions., For the following table:
CREATE TABLE Dbo.[CompanyType](
[TypeID] [bigint] IDENTITY(1,1) NOT NULL,
[Manufacturer] [bit] NULL,
[Trading] [bit] NULL,
[BuyingOffice] [bit] NULL,
[Agent] [bit] NULL,
[Wholesaler] [bit] NULL,
[Commission] [bit] NULL,
[Association] [bit] NOT NULL,
[BusinessService] [bit] NOT NULL,
[Other] [bit] NOT NULL,
[Photo] [image] NULL,
[CreateDate] datetime
CONSTRAINT [PK_CompanyType] PRIMARY KEY CLUSTERED
(
[TypeID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO
ALTER TABLE dbo.[CompanyType] ADD CONSTRAINT [DF_Company_PersianTax] DEFAULT ((9)) FOR [Taxpercent]
GO
ALTER TABLE dbo.[CompanyType] ADD CONSTRAINT [DF_Company_CreateDate] DEFAULT (getdate()) FOR [CreateDate]
GO
using a check constrain.
How to use check constrain for this model??
I tried by :
In the meantime I use SP to insert. Isn't it better to check for three or more true data there? At the moment of data entry as a parameter check
--parameter validation
if(#Manufacturer+#Trading+#BuyingOffice+#Agent+#Wholesaler+#Commission+#Association+#BusinessService+#Other)<= 3
Begin
Return
End
else
insert statement (...)
Using trigger like following query! check inserted, sum of column <= 3 rolback
CREATE TRIGGER usp_checksum3
ON dbo.companytype
AFTER insert
AS
BEGIN
SET NOCOUNT ON;
if (Select [Manufacturer]+[Trading]+[BuyingOffice]+[Agent]+[Wholesaler]+[Commission]+[Association]+[BusinessService]+[Other]
From inserted) <= 3
Return
END
Thanks for your tips
Consider using the following check constraint:
CREATE TABLE Dbo.[CompanyType](
[TypeID] [bigint] IDENTITY(1,1) NOT NULL,
[Manufacturer] [bit] NULL,
[Trading] [bit] NULL,
[BuyingOffice] [bit] NULL,
[Agent] [bit] NULL,
[Wholesaler] [bit] NULL,
[Commission] [bit] NULL,
[Association] [bit] NOT NULL,
[BusinessService] [bit] NOT NULL,
[Other] [bit] NOT NULL,
[Photo] [image] NULL,
[CreateDate] datetime
CONSTRAINT [PK_CompanyType] PRIMARY KEY CLUSTERED ([TypeID] ASC)
WITH (
PAD_INDEX = OFF,
STATISTICS_NORECOMPUTE = OFF,
IGNORE_DUP_KEY = OFF,
ALLOW_ROW_LOCKS = ON,
ALLOW_PAGE_LOCKS = ON,
OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY],
CONSTRAINT [PK_Company_Types] CHECK (
CAST([Manufacturer] AS INT)
+ CAST([Trading] AS INT)
+ CAST([BuyingOffice] AS INT)
+ CAST([Agent] AS INT)
+ CAST([Wholesaler] AS INT)
+ CAST([Commission] AS INT)
+ CAST([Association] AS INT)
+ CAST([BusinessService] AS INT)
+ CAST([Other] AS INT)
<= 3)
You don't need to implement additional logic in your stored procedure. The check constraint guarantees integrity, and apply equally to inserts performed from the SP or outside.
If you want to modify the existing table:
ALTER TABLE Dbo.[CompanyType]
ADD CONSTRAINT [Chk_CompanyType] CHECK (
CAST([Manufacturer] AS INT)
+ CAST([Trading] AS INT)
+ CAST([BuyingOffice] AS INT)
+ CAST([Agent] AS INT)
+ CAST([Wholesaler] AS INT)
+ CAST([Commission] AS INT)
+ CAST([Association] AS INT)
+ CAST([BusinessService] AS INT)
+ CAST([Other] AS INT)
<= 3)

How to copy column Data of one Table to another

I am using the code below:
Insert into JV(PurchaseID)
select PurchaseID from PurchaseReturnDetail
But when I execute the query it gives an error:
Cannot insert the value NULL into column 'column1', table 'database.table1'; column does not allow nulls.
Then my INSERT fails. What could be the issue?
The error says the table has a non-null constraint for the column. To change the column to allow nulls, run this query (for Oracle DB):
alter table TABLE_NAME modify (COLUMN_NAME null);
If first columns is identity column, make sure that auto increment is enabled for that column .
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[JV](
[JVID] [numeric](18, 0) IDENTITY(1,1) NOT NULL,
[JVInvoiceNo] [nvarchar](50) NULL,
[JVDate] [datetime] NULL,
[StoreID] [numeric](18, 0) NULL,
[BusinessID] [numeric](18, 0) NULL,
[UserID] [numeric](18, 0) NULL,
[Currency] [nvarchar](50) NULL,
[Rate] [decimal](18, 10) NULL,
[DueDate] [datetime] NULL,
[Reference] [nvarchar](50) NULL,
[RefID] [numeric](18, 0) NULL,
[Narration] [nvarchar](max) NULL,
[InvoiceRef] [nvarchar](50) NULL,
[Status] [nvarchar](50) NULL,
[Type] [nvarchar](50) NULL,
[PurchaseID] [numeric](18, 0) NULL,
CONSTRAINT [PK_JV] PRIMARY KEY CLUSTERED
(
[JVID] 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

Unable to set foreign key for my computed column

I can't set the foreign key for my advertisement table or should I say how do I add datatype for my computed column in employer table ? error details below
CREATE Table Employer
(
No Int NOT NULL IDENTITY(1,1),
EmployerID AS 'EID'+ CAST(No as VARCHAR(50)) PERSISTED NOT NULL ,
CONSTRAINT PK_Employer PRIMARY KEY CLUSTERED(EmployerID),
EUsername CHAR(20) NOT NULL,
EPassword CHAR(20) NOT NULL,
Name VARCHAR(20) NOT NULL,
Contact_Number INT NOT NULL,
Email CHAR(20) NOT NULL,
Company_Name CHAR(30) NOT NULL,
Current_Position VARCHAR(30) NULL
);
CREATE Table Advertisement
(
No Int NOT NULL IDENTITY(1,1),
AdvertisementID AS 'AID'+ CAST(No as VARCHAR(10)) PERSISTED ,
CONSTRAINT PK_Advertisement PRIMARY KEY CLUSTERED(AdvertisementID) ,
Employer_ID VARCHAR(10) Foreign Key References Employer(EmployerID) NOT NULL,
Company_Name VARCHAR(30) NOT NULL,
Company_Location CHAR(30) NULL,
Job_Position VARCHAR(30)NOT NULL,
Job_Description VARCHAR(100) NULL,
Skills_Requirement VARCHAR(100) NULL,
Education_Requirement CHAR(50) NOT NULL,
Salary CHAR(20) NOT NULL
);
This is the error I keep getting :
Msg 1753, Level 16, State 0, Line 27
Column 'Employer.EmployerID' is not the same length or scale as referencing column 'Advertisement.EmployerID' in foreign key 'FK__Advertise__Emplo__07C12930'. Columns participating in a foreign key relationship must be defined with the same length and scale.
Msg 1750, Level 16, State 0, Line 27
Could not create constraint or index. See previous errors.
note that the foreign key relationship must be defined with the same length and scale for both foreign key and primary key
so you must set EmployerID field to varchar(50) in advertisement table
Its recommended to use BIGINT auto increment field type for EmployerID.
and use Employer table's EmployerID field as you foreign key.
CREATE TABLE [Employer](
[EmployerID] [bigint] IDENTITY(1,1) NOT NULL,
[EUsername] [char](20) NOT NULL,
[EPassword] [char](20) NOT NULL,
[Name] [varchar](20) NOT NULL,
[Contact_Number] [int] NOT NULL,
[Email] [char](20) NOT NULL,
[Company_Name] [char](30) NOT NULL,
[Current_Position] [varchar](30) NULL,
CONSTRAINT [PK_Employer] PRIMARY KEY CLUSTERED
(
[EmployerID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
CREATE TABLE [Advertisement](
[AdvertisementID] [bigint] IDENTITY(1,1) NOT NULL,
[fk_Employer_ID] [bigint] NOT NULL,
[Company_Name] [varchar](30) NOT NULL,
[Company_Location] [char](30) NULL,
[Job_Position] [varchar](30) NOT NULL,
[Job_Description] [varchar](100) NULL,
[Skills_Requirement] [varchar](100) NULL,
[Education_Requirement] [char](50) NOT NULL,
[Salary] [char](20) NOT NULL,
CONSTRAINT [PK_Advertisement] PRIMARY KEY CLUSTERED
(
[AdvertisementID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
ALTER TABLE [Advertisement] WITH CHECK ADD CONSTRAINT [FK_Advertisement_Employer] FOREIGN KEY([fk_Employer_ID])
REFERENCES [Employer] ([EmployerID])
ALTER TABLE [Advertisement] CHECK CONSTRAINT [FK_Advertisement_Employer]

How to insert Foreignkey value into a table which doesnt exist yet

I have a situation, I have two tables namely ,User and Company .
Here is my User table :
CREATE TABLE [dbo].[User](
[UserId] [int] IDENTITY(1,1) NOT NULL,
[UserName] [nvarchar](500) NOT NULL,
[Password] [nvarchar](500) NOT NULL,
[CompanyId] [int] NULL,
[LastModUserId] [int] NOT NULL,
[LastModDttm] [datetime] NOT NULL,
CONSTRAINT [PK_User] PRIMARY KEY CLUSTERED
(
[UserId] 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].[User] WITH CHECK ADD CONSTRAINT [FK_User_Company] FOREIGN KEY([CompanyId])
REFERENCES [dbo].[Company] ([CompanyId])
GO
ALTER TABLE [dbo].[User] CHECK CONSTRAINT [FK_User_Company]
GO
ALTER TABLE [dbo].[User] WITH CHECK ADD CONSTRAINT [FK_User_User1] FOREIGN KEY([LastModUserId])
REFERENCES [dbo].[User] ([UserId])
GO
ALTER TABLE [dbo].[User] CHECK CONSTRAINT [FK_User_User1]
GO
Here is my Company Table :
CREATE TABLE [dbo].[Company](
[CompanyId] [int] IDENTITY(1,1) NOT NULL,
[CompanyName] [nvarchar](500) NOT NULL,
[Address1] [nvarchar](500) NULL,
[Address2] [nvarchar](500) NULL,
[LastModUserId] [int] NOT NULL,
[LastModDttm] [datetime] NOT NULL,
CONSTRAINT [PK_Company] PRIMARY KEY CLUSTERED
(
[CompanyId] 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].[Company] WITH CHECK ADD CONSTRAINT [FK_Company_User] FOREIGN KEY([LastModUserId])
REFERENCES [dbo].[User] ([UserId])
GO
ALTER TABLE [dbo].[Company] CHECK CONSTRAINT [FK_Company_User]
GO
My problem :
I want to create a company record,I haven't created a user yet.When I Insert into the LastModUserId columun it will throw the error "Cannot Insert the value NULL into column 'LastModUserId' ,table MYDb.dbo.Company' , column does not allow nulls.INSERT fails.
If I try to insert a record into the User Table ,there is also the same problem ,there is CompanyId column,which doesn't allow nulls either
How do I handle this situation ?
Disable constraint to enter super record.
ALTER TABLE [User] NOCHECK CONSTRAINT [FK_User_User1];
GO
ALTER TABLE [User] NOCHECK CONSTRAINT [FK_User_Company];
GO
DECLARE #USERID AS INT, #COMPANYID AS INT;
SELECT #USERID = 1, #COMPANYID = 1;
SET IDENTITY_INSERT [User] ON;
INSERT INTO [User](
[UserId],
[UserName],
[Password],
[CompanyId],
[LastModUserId],
[LastModDttm]
)
select
#USERID,
'Super',
'Passw0rd',
1,
1,
getdate();
SET IDENTITY_INSERT [User] OFF;
SET IDENTITY_INSERT [Company] ON;
insert into [Company](
[CompanyId],
[CompanyName],
[Address1],
[Address2],
[LastModUserId],
[LastModDttm])
select
#COMPANYID,
'cOMANY a',
'Address 1',
'Address 2',
#USERID,
getdate();
SET IDENTITY_INSERT [Company] OFF;
go
ALTER TABLE [User] CHECK CONSTRAINT [FK_User_User1];
GO
ALTER TABLE [User] CHECK CONSTRAINT [FK_User_Company];
GO

SQL Foreign key issue with Primary Keys

I do have a problem connecting two tables on MSSQL Management studio.
My goal is connect tables by foreign key and if I delete user I want 2nd table entry will be deleted automatically. I plan to use DELETE Cascade method for that.
User:
CREATE TABLE [dbo].[Users](
[ID] [bigint] IDENTITY(1,1) NOT NULL,
[Email] [nvarchar](89) NOT NULL,
[Name] [nvarchar](25) NOT NULL,
[Midname] [nvarchar](25) NOT NULL,
[Surname] [nvarchar](25) NOT NULL,
[Phone] [varchar](15) NOT NULL,
[Country] [smallint] NOT NULL,
[Manager] [nvarchar](89) NOT NULL,
[Referrer] [nvarchar](89) NOT NULL,
[Rank] [tinyint] NOT NULL,
CONSTRAINT [PK_Users] PRIMARY KEY CLUSTERED
(
[Email] 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
Email is Primary key
Payments:
CREATE TABLE [dbo].[Investments](
[ID] [bigint] NOT NULL,
[Investor] [nvarchar](89) NOT NULL,
[Sum] [decimal](19, 4) NOT NULL,
[Currency] [smallint] NOT NULL,
[Credit] [decimal](19, 4) NOT NULL,
[CreditRate] [decimal](19, 4) NOT NULL,
[Rate] [tinyint] IDENTITY(1,1) NOT NULL,
[Date] [smalldatetime] NOT NULL,
[Comment] [nvarchar](max) NOT NULL,
CONSTRAINT [PK_Investments] PRIMARY KEY CLUSTERED
(
[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
ID is Primary key
My FK should be like USER->PAYMENTS or PAYMENTS->USER?
When I am trying to connect User -> Payments using foregn key by Email -> Investor, it tell me such error:
The columns in table 'Payments' do not match an existing primary key or UNIQUE constraint.
Could you please explain me where problem is? And what I am doing wrong?
Change your structure to:
CREATE TABLE [dbo].[Users](
[ID] [bigint] IDENTITY(1,1) NOT NULL,
[Email] [nvarchar](89) NOT NULL,
[Name] [nvarchar](25) NOT NULL,
[Midname] [nvarchar](25) NOT NULL,
[Surname] [nvarchar](25) NOT NULL,
[Phone] [varchar](15) NOT NULL,
[Country] [smallint] NOT NULL,
[Manager] [nvarchar](89) NOT NULL,
[Referrer] [nvarchar](89) NOT NULL,
[Rank] [tinyint] NOT NULL);
ALTER TABLE [Users]
ADD CONSTRAINT PK_UsersID PRIMARY KEY (ID);
and then
CREATE TABLE [dbo].[Investments](
[ID] [bigint] NOT NULL,
[UserID] [bigint] NOT NULL,
[Sum] [decimal](19, 4) NOT NULL,
[Currency] [smallint] NOT NULL,
[Credit] [decimal](19, 4) NOT NULL,
[CreditRate] [decimal](19, 4) NOT NULL,
[Rate] [tinyint] IDENTITY(1,1) NOT NULL,
[Date] [smalldatetime] NOT NULL,
[Comment] [nvarchar](max) NOT NULL);
ALTER TABLE Investments
ADD CONSTRAINT PK_InstestmentsID PRIMARY KEY (ID);
ALTER TABLE Investments
ADD CONSTRAINT FK_UsersInvestments
FOREIGN KEY (UserID)
REFERENCES Users(ID);
Then join Users.ID on Investments.UserID
I searched for the error message you are seeing (without the table name) and the general consensus
seems to be that a PRIMARY KEY or UNIQUE contraint has not been correctly set in your tables. The error also tells me you are (probably) using SQL Server.
From technet.microsoft.com:
The columns on the primary key side of a foreign key relationship must
participate in either a Primary Key or a Unique Constraint. After
setting up a Primary Key or a Unique constraint for one of the tables
you've selected, you can then define other relationships for that
table.
Check your PRIMARY KEYS in both tables. Without the actual DDL of your tables it's difficult to be of more help.
EDIT: You have Email as the PRIMARY KEY in your Users table but I do not see an Email field in the Investments table. Which fields are you joining on in your contraint?