FK Constraint From One Column To Two Different Tables
Apr 13, 2012I have a requirement where one column of a table is supposed to have two foreign key constraints i.e. it can be referring to two different columns in two tables.
View 1 RepliesI have a requirement where one column of a table is supposed to have two foreign key constraints i.e. it can be referring to two different columns in two tables.
View 1 RepliesWe have a database where many tables have a field that has to be lengthened. In some cases this is a primary key or part of a primary key. The table in question is:-
/****** Object: Table [dbo].[DTb_HWSQueueMonthEnd] Script Date: 09/25/2014 14:05:09 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[DTb_HWSQueueMonthEnd](
[Code] ....
The script I am using is
DECLARE@Column varchar(100)--The name of the column to change
DECLARE@size varchar(5)--The new size of the column
DECLARE @TSQL varchar(255)--Contains the code to be executed
DECLARE @Object varchar(50)--Holds the name of the table
DECLARE @dropc varchar(255)-- Drop constraint script
[Code] ....
When I the the script I get the error message Could not create constraint. See previous errors.
Looking at the strings I build
ALTER TABLE [dbo].[DTb_HWSQueueMonthEnd] DROP CONSTRAINT PK_DTb_HWSQueueMonthEnd
ALTER TABLE [dbo].[DTb_HWSQueueMonthEnd] Alter Column [Patient System Number] varchar(10)
ALTER TABLE [dbo].[DTb_HWSQueueMonthEnd] ADD CONSTRAINT PK_DTb_HWSQueueMonthEnd PRIMARY KEY NONCLUSTERED ([Patient System Number] ASC,[Episode Number] ASC,[CensusDate] ASC)
WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, IGNORE_DUP_KEY = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
They all seem fine except the last one which returns the error
Msg 8111, Level 16, State 1, Line 1
Cannot define PRIMARY KEY constraint on nullable column in table 'DTb_HWSQueueMonthEnd'.
Msg 1750, Level 16, State 0, Line 1
Could not create constraint. See previous errors.
None of the fields I try to create the key on are nullable.
Is it possible to have a constarint between two tables based on a FK relationship and a value based on another column. For example to have a valid record in table b the TableA_ID value needs to exist in tableA and the charge Value can't be null. So row number 3 would be invalid in table B in this example.
TableA
IDCharge_Value
1100
2Null
34
4Null
TableB
TableB_IDTableA_IDSome other data
1 1 A
2 3 B
3 4 C
I know to disable all constraint in a table just :ALTER TABLE table_A CHECK CONSTRAINT ALLbut how to disable ALL tables at the same time?Thanks anyway
View 7 Replies View RelatedHi,The following request select a constraint from TABLE_CONSTRAINT withthe name specified in the where clause:select * from INFORMATION_SCHEMA.TABLE_CONSTRAINTS whereconstraint_name = 'FK__51OtherParties__51Claims'It returns:http://graphicsxp.free.fr/constraint.JPGSo I have TABLE_NAME that correspond to the first table involved in theconstraint, but how do I get 51Claims ????Thank you
View 2 Replies View RelatedIs it possible to create a unique constraint on two tables?In mssql2000?
View 7 Replies View RelatedHow can you indicate that a FOREIGN KEY constraint references twocolumns in two different tables?"SQL Server Books Online" show an example of how to reference twocolumns in the SAME table:REFERENCES ref_table [ ( ref_column [ ,...n ] )Here is the error and the 'bad' SQL code:Server: Msg 8148, Level 16, State 1, Line 4More than one column FOREIGN KEY constraint specified for column'UserOrGroupId', table 'salesforce3.dbo.AccountShare'.CREATE TABLE salesforce3.dbo."AccountShare" ("Id" varchar(18) PRIMARYKEY , ... , "UserOrGroupId" varchar(18) CONSTRAINTFK_UserOrGroupId6349 FOREIGN KEY REFERENCES "User"(Id) REFERENCES"Group"(Id) , ... )
View 2 Replies View RelatedHi,
I don't know if this is possible, i believe not, so I'm here to ask the experts if is possible to have a foreign key constraint that references the key of one of two tables.
Like this:
I have 3 tables: TABLE X, TABLE A and TABLE B
Is it possible to the FK on TABLE X refernce the PK of TABLE A OR TABLE B?
If yes, how can I do this?
If not, I need to have a fourth table, so TABLE X references TABLE A and TABLE Y references TABLE B.
Thanks!
Is it possible to define a referential constraint between two tables in two different databases (on two servers)? Or are there beter best practices methods/products to achieve this result.
View 4 Replies View RelatedGreetings all!
How can I enforce a foreign key constraint when I have two tables each one residing on a different database?
Thanks for your help in advance.
Hmm,
I'm creating a table that contains information from two other tables. I'd like to have a constraint on some columns so that thay can only contain information that exists in the other two tables. This is what I got:
create table dbo.KUSE_Bills
(
SERVICE_ID int IDENTITY(1,1) NOT NULL primary key,
BILLDATE datetime NOT NULL,
CNAME varchar(100) NOT NULL,
SNAME varchar(100) NOT NULL,
PRICE money NOT NULL,
UNIT varchar(50) NOT NULL,
NUMBER integer NOT NULL,
BILLSUM money NOT NULL
)
GO
I tried something like this:
create table dbo.KUSE_Bills
(
SERVICE_ID int IDENTITY(1,1) NOT NULL primary key,
BILLDATE datetime NOT NULL,
CNAME varchar(100) NOT NULL,
SNAME varchar(100) NOT NULL,
PRICE money NOT NULL,
UNIT varchar(50) NOT NULL,
NUMBER integer NOT NULL,
BILLSUM money NOT NULL
CONSTRAINT chk_cname CHECK (CNAME NOT IN (
SELECT CNAME FROM KUSE_Customer))
)
GO
But subqueries are not allowed...
So how can I do it?
What query gives me the list of child tables accessing a unique key (But Not PK) for a given table?
For. E.g. In the folloiwng scenario I should get o/p as t3
create table t1 (id1 int primary key , id2 int unique )
create table t2 (id1 int references t1(id1))
create table t3 (id2 int references t1(id2))
------------------------
I think, therefore I am - Rene Descartes
Hi,DDLs and DMLs:create table #job (jobID int identity(1,1) primary key, jobNamevarchar(25) unique not null, jobEndDate dateTime, jobComplete bitdefault(0), check (([JobEndDate] is null and [JobComplete] = 0) OR([JobEndDate] is not null and [JobComplete] = 1)));Q1 with check constraint:sample dagtainsert into #job (jobName)values('first job');transaction Aupdate #jobset jobEndDate = '12/19/2003', JOBCOMPLETE=1where jobID = 3;RESULTSET/STATUS = Successupdate #jobset jobEndDate = NULL, JOBCOMPLETE=0where jobID = 3;RESULTSET/STATUS = Successtransaction Cupdate #jobset jobEndDate = '12/19/2003'where jobID = 3;RESULTSET/STATUS = Failurehow come check constraint can't set a value which is preset in thecheck constraint? If it's the way how it works with MS SQL Server2000, well, IMHO, it's limiting because the above transaction C is avalid one. Or maybe check constraint is not fit for this purpose?Maybe, it doesn't make much sense for me to go into Q2 but I'll try-- create job's child table, taskcreate table #task (taskID int identity(1,1) primary key, taskNamevarchar(25) unique not null, taskEndDate dateTime, taskComplete bitdefault(0), jobID int not null references #job (jobID));-- skip check constraint for taskEndDate and taskComplete for nowNow, the Business Rule says,1) if all tasks are complete then automatically set jobComplete forthe #job table to yes;2) the jobEndDate in the #job table must be >= the last/MaxtaskEndDateI tend to think trigger would slow down data update quite a bit, so,try to stay away for this purpose if possible.Always appreciate your idea.
View 2 Replies View Related
Hello,
I have a header and detail table. I want to create a constraint on the detail table, based on a value it's linked to in the header table. If the bit is checked in header then a unique value is required , if it's not checked then a NULL value is acceptable.
Many thanks in advance.
I like to use the management console to design tables, but have
been unable to figure out how to add a unique column constraint.
I have a primary key defined in col1 and want to make col2, char(10),
unique, but keep col1 as the primary key.
I have tried the Check constraint menu path, but do not know how
to write the expression.
If I go along the Indexes/Key path, I am forced to change the primary
key which I do not want to do.
Can anyone help?
TIA, Joe
Hi allWould there be a easy way to find the column name(s) which constitutea Primary constraint for a table through navigating the systemcatalogs.I found that the PK Constraint object in syscontraints is showing thecolid = 0.TIANorman
View 2 Replies View Related
Hello !
I am using Microsoft SQL Server 2000
I am trying to drop a column that has a constraint, executing the script inside a transaction:
BEGIN TRANSACTION
ALTER TABLE MOPTeste DROP CONSTRAINT FK_IDMOPPais
ALTER TABLE MOPTeste DROP COLUMN IDMOPPais
COMMIT
If i dont commit the drop constraint, it wont let me drop the column
Solutions?
I receive the following error when creating a CHECK constraint that references another column. According to the good old Wrox SQL Server book, I'm using the correct syntax. Anyone have any ideas???
Thanks in advance!
Server: Msg 8141, Level 16, State 1, Line 1
Column CHECK constraint for column 'end_date' references another column, table 'Session'.
Here's an example of the script that I'm using:
CREATE TABLE Session (
session_key char(18) NOT NULL,
course_key char(18) NOT NULL,
site_key char(18) NOT NULL,
instructor_key char(18) NOT NULL,
start_date smalldatetime NULL,
end_date smalldatetime NULL
CHECK (end_date >= start_date)
)
.
How do I alter a column check constraint?
I have the table:
CREATE TABLE Mytable(
mykey integer,
mycol integer
CHECK(mycol BETWEEN 1 AND 2)
PRIMARY KEY(mykey))
How do I change the constraint to
CHECK(mycol BETWEEN 0 AND 2)
...without losing any data?
Thanks!
Jim
Hi.
I was wondering how I should go about doing this thing. I need to put a value in a column that is based on values on other columns in the same row.
When this statement executes I need to put a value in Col3.
insert into myTable(Col1, Col2)
values(25, -14)
Something like so:
if(Col1 >0 AND Col2 <0)
set Col3 = Col1 - Col2
else
set Col3 = Col1;
I don't now quite how to solve this. I am really going to need this value in a column. Calculating the value at retrieval is not on option...
I appreciate all help. I'm using SQL Server 2005.
Thanks!
I can't seem to get the syntax correct for ALTERing an existing column with a default constraint. I've been to Help and BOL. There are examples that show how to use the ALTER command to add a column with a default constraint but not how to do it on an existing column.
Any help would be appreciated.
Sidney Ives
Can anyone please tell me how can i create a uniqueness contraint on part of column and index that part too. i.e.
consider the following table.
table A
Col1
furadfaf
fsradfasd
dddafadsf
hjfhdfjakdj
now i want only left three characters of the Col1 to be unique and indexed.
any idea ??????
I have a producer table with a nullable column that stores SSN's. In some cases producers inherit SSN's from other producers. These records will have a null producer.ssn and a record stored in a child table to track the inheritance. Anyway, I've found two techniques to enforce uniqueness on a nullable column and wanted to get opinions as to which was better. First, write a trigger. Second, create a computed column that has a unique constraint on it. The computed column would use the SSN if not NULL Else use the PK identity value of the record. EXAMPLE DML:CREATE TABLE test ( ssn CHAR(9) NULL, testId INT identity(1,1) NOT NULL, ComputedConstraint AS CASE WHEN ssn IS NULL THEN CAST(testId AS CHAR(9)) ELSE ssn END, UNIQUE (ComputedConstraint)) Any comments would be greatly appreciated.
View 6 Replies View RelatedWhat do you guys think about creating a unique constraint on a string column in a database?
Currently, I'm enforcing uniqueness through the stored procedure that inserts rows into the table. E.g.
PROCEDURE addRow( name )
DECLARE r INT;
SELECT COUNT(*) INTO r FROM foo WHERE foo.foo_name = name;
IF r = 0 THEN
INSERT INTO foo (foo_name) values(name);
ELSE
// Not unique throw an error
END PROCEDURE
What do you guys think?
I am importing data from a flat, comma delimited text file. It appears to properly import all the records and then on the last record it give me the error
INSERT statement conflicted with COLUMN FOREIGN KEY constraint for 'EOR_ITE_REF_EOR'.
Then it goes on to tell me the database, table and column in which the problem occured which is the first column in the table. It looks like it doesn't like the end of the file for some reason (EOR, end of record?) so I tried deleting the last record from the file and it still does it. I do have a file that I have imported that worked so I tried copying the last record of that file and pasting it into the last record of the file I wanted but that did not work either. The ends of file that works and the file that doesn't work look the same and I can find nothing on 'EOR_ITE_REF_EOR'. Any help would be appreciated.
Running an insert into a table where a column has a constraint for unique records
i have an autonumber pk that increments but numbers are not in sequence etc. if constraints are found
e.g.
10 records are inserted but only 2 are unique but there is a gap of 8 in the PK autoincrement value (it's like the unique records that were not inserted are still being recorded by the autoincrement).
I am very new to sql and I have got this doubt.
CREATE TABLE employee
{ EMP-ID VARCHAR UNIQUE,
DESIG VARCHAR UNIQUE,
SALARY INT };
Probably this is worst table ever created :).Now How to drop UNIQUE constraint on only column lets DESIG.
if i write
ALTER TABLE employee
DROP CONSTRAINT myuniqueconstraint;
will drop constraints on both columns which I dont want.
Any query that remove UNIQUE CONSTRAINT only on DESIGN column.
and one more clarification,
ALTER TABLE employee
MODIFY SALARY INT NOT NULL;
ALTER TABLE employee
ALTER COLUMN SALARY INT NOT NULL;
which of the above two is right query to add NOT NULL constraint to the above employee TABLE?
I don't immediately find if this is possible but hope someone can give me an answer:
is it possible to make a unique constraint over 2 columns but only when 1 column has a specific value ?
Example: table (tableid, instancetype, instancename, ..)
instancetype can be A or B
if it is A then instancename must be unique
but for B instancename is not unique as these are copies from A
only solution I can think of is to make a trigger on an insert to check what the instancetype is and do a select to see if the name already exists in the table or not..
are there other solutions to make a constraint like this ?
Aeneas.
Is it possible to create a unique constraint to a column from anothertable? For example:tb_current:current_names--------------aaabbbtb_new:new_name--------cccNow I want to create a constraint on tb_new.new_name to be unique withrespect to tb_current.current_names. However, tb_new.new_name shouldnot be unique to itself. So I should not be able to insert 'aaa' totb_new.new_name. But I should be able to insert 'ccc' totb_new.new_name.Here's the script to reproduce this example:create table tb_current(current_names varchar(10))create table tb_new(new_name varchar(10))insert tb_current values ('aaa')insert tb_current values ('bbb')insert tb_new values ('ccc')select * from tb_currentselect * from tb_newinsert tb_new values ('aaa') -- this should NOT be allowedinsert tb_new values ('ccc') -- this should be allowed
View 3 Replies View Related
Hello!
I am trying to alter a table adding a column with foreignkey constraint. The table that holds the primary key in that relation has data, so i am not being able to execute the alter statement.
This is the error:
Server: Msg 547, Level 16, State 1, Line 1
ALTER TABLE statement conflicted with COLUMN FOREIGN KEY constraint 'FK_MOPAeroportoICAO_IDMOPAlimentacaoFerroviaTipo'. The conflict occurred in database 'MOP', table 'MOPAlimentacaoFerroviaTipo', column 'IDMOPAlimentacaoFerroviaTipo'.
This is the script:
ALTER TABLE MOPAeroportoICAO
ADD IDMOPAlimentacaoFerroviaTipo [int] DEFAULT 0 NOT NULL
CONSTRAINT [FK_MOPAeroportoICAO_IDMOPAlimentacaoFerroviaTipo] FOREIGN KEY
REFERENCES MOPAlimentacaoFerroviaTipo (IDMOPAlimentacaoFerroviaTipo)
How can i turn of check when i add the foreign key ?
Thanks in advance
I need to create constraint in column to add only alphabet .
like "adc" ,"sdfsd" and not "1234adfd".plz reply soon.
When generating a check constraint to guarantee that a character column cannot be blank is it best to use comparison operators such as col1 <> '' or to use LEN(col1) > 0? Note that the column in marked as not nullable.
View 5 Replies View RelatedHi,
I have a table with one of its column VARBINARY(MAX).
I want to make sure that the values in this VARBINARY(MAX) column is unique.
SQL Server doesn;t allow to create Unique Constraint over VARBINARY fields - whats the best workaround for ensuring uniqueness on VARBINARY columns.
Thanks,
Loonysan