Unable to set foreign key for my computed column - sql

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]

Related

Conversion failed when converting date and/or time from character string. What could be wrong?

INSERT INTO dbo.SaleNew(ENQ_AID,DOCKET_NO,SALE_TYPE,VEHICLE_MODEL,SALE_DATE,BOOKING_DATE,DELIVERY_DATE,
DEALER_NAME,ENQ_GEN_BY,EXEC_NAME,USER_CR,DATE_CR) SELECT '6','2','0','TEST','2016-05-01','2016-05-10','2016-05-15',
'ABC','S I','V B','1',SWITCHOFFSET(SYSDATETIMEOFFSET(), '+05:30')
What could be wrong with this query?
Also tried:
INSERT INTO dbo.SaleNew(ENQ_AID,DOCKET_NO,SALE_TYPE,VEHICLE_MODEL,SALE_DATE,BOOKING_DATE,DELIVERY_DATE,
DEALER_NAME,ENQ_GEN_BY,EXEC_NAME,USER_CR,DATE_CR) SELECT '6','2','0','TEST',CONVERT(DATE,'01/05/2016',103),CONVERT(DATE,'10/05/2016',103),
CONVERT(DATE,'15/05/2016',103),'ABC','S I','V B','1',SWITCHOFFSET(SYSDATETIMEOFFSET(), '+05:30')
This is the create table query:
CREATE TABLE [dbo].[SaleNew](
[SALE_ID] [int] IDENTITY(1,1) NOT NULL,
[ENQ_AID] [bigint] NOT NULL,
[DOCKET_NO] [varchar](50) NOT NULL,
[VEHICLE_MODEL] [varchar](100) NOT NULL,
[SALE_DATE] [date] NULL,
[BOOKING_DATE] [date] NULL,
[DELIVERY_DATE] [date] NULL,
[DEALER_NAME] [date] NULL,
[ENQ_GEN_BY] [varchar](100) NULL,
[EXEC_NAME] [varchar](100) NULL,
[USER_CR] [int] NULL,
[DATE_CR] [date] NULL,
[USER_UP] [int] NULL,
[DATE_UP] [date] NULL,
[SALE_TYPE] [int] NOT NULL,CONSTRAINT [PK_SaleNew] PRIMARY KEY CLUSTERED (
[SALE_ID] ASC )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON ) ON [PRIMARY]
What could be the reason?
DEALER_NAME type is defined as DATE but you want to INSERT a VARCHAR type value ABC in it.
Execute following query in order to edit the mentioned column type, then Execute your INSERT query.
ALTER TABLE [dbo].[SaleNew]
ALTER COLUMN [DEALER_NAME] VARCHAR(50) NULL

Adding Primary keys and a Relationship to tables

I have compiled the following as an example of what i have done so far and would like to know how i should continue:
CREATE TABLE tblMembers
(
Member_ID int,
Name varchar(255)
);
CREATE TABLE tblHorses
(
Horse_ID int,
Name varchar(255),
Age int(10),
Member_ID int(10)
);
So i would like to specify both Member_ID and Horse_ID as the PK and create the relationship between tblMembers and tblHorses using Member_ID
I would also like to make the ID columns auto incremental
Thank you in advance
Is this what you ware asking?
CREATE TABLE tblMembers (
Member_ID int identity(1, 1) not null primary key
Name varchar(255)
);
CREATE TABLE tblHorses (
Horse_ID int identity(1, 1) not nullprimary key
Name varchar(255),
Age int,
Member_ID int references tblMembers(member_id)
);
Storing something like "age" in a column is a really bad idea. After all, age continually changes. You should be storing something like the date of birth.
CREATE TABLE tblMembers
(
Member_ID int AUTO_INCREMENT,
Name varchar(255)
PRIMARY KEY (MEMBER_ID)
);
CREATE TABLE tblHorses
(
Horse_ID int,
Name varchar(255),
Age int(10),
FOREIGN KEY (MEMBER_ID) REFERENCES tblMembers(MEMBER_ID)
PRIMARY KEY (HORSE_ID)
);
Following W3Schools' examples.
Use this. Fiddler Demo
Refer this for creating Primary Key,Foreign Key, Identity .
CREATE TABLE tblMembers
(
Member_ID int IDENTITY(1,1) Primary Key,
Name varchar(255)
);
CREATE TABLE tblHorses
(
Horse_ID int IDENTITY(1,1) Primary Key,
Name varchar(255),
Age int,
Member_ID int Foreign key (Member_ID) REFERENCES tblMembers(Member_ID)
);
Note: MS SQL doesn't support length in Integer Type.
try this
CREATE TABLE [dbo].[tblMembers](
[Member_ID] [int] IDENTITY(1,1) NOT NULL,
[Name] [varchar](255) NOT NULL,
CONSTRAINT [PK_tblMembers] PRIMARY KEY CLUSTERED
(
[Member_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
CREATE TABLE [dbo].[tblHorses](
[Horse_ID] [int] IDENTITY(1,1) NOT NULL,
[Name] [varchar](255) NULL,
[Age] [int] NULL,
[Member_ID] [int] NOT NULL,
CONSTRAINT [PK_tblHorses] PRIMARY KEY CLUSTERED
(
[Horse_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].[tblHorses] WITH CHECK ADD CONSTRAINT [FK_tblHorses_tblMembers] FOREIGN KEY([Member_ID])
REFERENCES [dbo].[tblMembers] ([Member_ID])
GO
ALTER TABLE [dbo].[tblHorses] CHECK CONSTRAINT [FK_tblHorses_tblMembers]
GO
For Auto Incremental, you have to set PK column as identity(seed, value)
CREATE TABLE tblMembers (
Member_ID INT IDENTITY(1, 1) NOT NULL PRIMARY KEY
Name VARCHAR(255)
);
CREATE TABLE tblHorses (
Horse_ID INT IDENTITY(1, 1) NOT NULL PRIMARY KEY
Name VARCHAR(255),
Age INT,
Member_ID int REFERENCES tblMembers(Member_id)
);
Try below
CREATE TABLE tblMembers (
Member_ID int identity(1, 1) not null
Name varchar(255)
PRIMARY KEY (Member_ID )
);
CREATE TABLE tblHorses (
Horse_ID int identity(1, 1) not null
Name varchar(255),
Age int,
PRIMARY KEY (Horse_ID)
Member_ID int references tblMembers(member_id)
);

foreign key relationships on delete cascade on update cascade

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

Date time index sql server 2005

I know this is a common topic but i stil feel my scenario requires some custom advice. I was selecting from a table the other day and it took me an AGE to select on a datetime column that has not been indexed. I want to index this, only problem ebing is that the "production" 2005 box i am unfamiliar with and how it will handle the index creation. With that in mind i am wondering what the safest way for me to create an index on the table is. All the details i think people will need are below (i hope) :
Index to be created on field 5 (possibly field4 also)
Table 1 definition:
CREATE TABLE [dbo].[TABLE 1](
[ID] [uniqueidentifier] NOT NULL CONSTRAINT [DF_BLA] DEFAULT (newid()),
[field1] [nvarchar](7) NULL,
[field2] [nvarchar](10) NULL,
[field3] [nvarchar](2) NULL,
[field4] [datetime] NULL,
[field5] [datetime] NULL,
[field6] [smallint] NULL,
[field7] [nvarchar](1) NULL,
[field8] [nvarchar](7) NULL,
[field9] [nvarchar](60) NULL,
[field10] [smallint] NULL,
[field11] [nvarchar](15) NULL,
[field12] [datetime] NULL,
CONSTRAINT [PK_ID] 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]
Total count of rows in Table 1 : 2926836

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?