Get All Foreignkey Contraints

Sep 28, 2007



Hi, I want know how can I to build a query to get all the foreignkey contrains exist between tables using the sys tables, for example if the user select this two tables:

dbo.cat_states -> with this fields -> id_state & desc
dbo.cat_universities -> with this fields -> id_state, id_university & desc_university

I want get something like this:

dbo.universities.id_state = dbo.states.id_state


tks 4 help
Leo

View 1 Replies


ADVERTISEMENT

How To Get Tablename / ForeignKey And Constraints

Sep 19, 2013

I have written the Query in which i am getting TableName,Columns,Precision but how can i get Table related Foreign key and Constraints

SELECT DISTINCT
QUOTENAME(SCHEMA_NAME(tb.[schema_id])) AS 'Schema',
QUOTENAME(OBJECT_NAME(tb.[OBJECT_ID])) AS 'Table',
C.NAME AS 'Column',
T.NAME AS 'DataType',
C.max_length,
C.is_nullable,
c.precision,
c.scale

[code]...

View 4 Replies View Related

ForeignKey Reference With Another Database

Apr 29, 2008



Hi All,

I have a table [Vendor] in first database SAMPLEDB. And i have another table [Contract] in another database TESTDB. I need a foreign key in the [Contract] table (which is in TESTDB database) is reference to the other table [Vendor] which is present in the SAMPLEDB.
When i try to creating them through SQL, i received the following error message :

Msg 1763, Level 16, State 0, Line 1
Cross-database foreign key references are not supported. Foreign key 'SAMPLEDB..VENDOR'.


Is that possible to refer foreign key in external database or not?
If possible, please give solution for this. If not possible, please suggest some alternate way.


Thanks in Advance

View 8 Replies View Related

ForeignKey Using INFORMATION_SCHEMA.TABLES As PrimaryKeyTable

Oct 12, 2006

Hi,

I have a "master" table that holds the names of data tables (one record in the "master" table for each "data" table).

Can I create a ForeignKey constraint that will prevent the "master" table records from being removed if the cooresponding "data" table exists? Is the way to do this to use INFORMATION_SCHEMA.TABLES as the PrimaryKeyTable for the ForeignKey?

Thanks!

View 1 Replies View Related

ForeignKey Constraint From A Lookup Table

Aug 5, 2007

Hi,

I'm trying to figure out how to setup a Constraint (Foreign Key?) from a lookup table.

For the following example, I want to constrain to constrain so that a Car.ParkingSpotNumber is unique for a given ParkingFacility.

Any thoughts?

Thanks!

Andy

Here's the scenario:
CAR table:
Id (PrimaryKey)
LicensePlateNumber
ParkingSpotNumber

PARKINGFACILITY__CAR__LOOKUP table:
Id (PrimaryKey)
CarId (Foreign Key to Car.Id)
ParkingFacilityId (Foreign Key to ParkingFacility)

PARKINGFACILITY table:
Id (PrimaryKey)

PARKINGLOT table:
Id (Foreign Key to ParkingFacility.Id) (PrimaryKey)
Address

PARKINGGARAGE table:
Id (Foreign Key to ParkingFacility.Id) (PrimaryKey)
Address


Here's the T-SQL code to make a SQLServer2005 database for this scenario:


SET ANSI_NULLS ON

GO

SET QUOTED_IDENTIFIER ON

GO

IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Car]') AND type in (N'U'))

BEGIN

CREATE TABLE [dbo].[Car](

[Id] [bigint] NOT NULL,

[CustomerName] [nvarchar](50) NOT NULL,

[ParkingSpotNumber] [int] NOT NULL,

CONSTRAINT [PK_Customer] 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]

END

GO

SET ANSI_NULLS ON

GO

SET QUOTED_IDENTIFIER ON

GO

IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[ParkingFacility]') AND type in (N'U'))

BEGIN

CREATE TABLE [dbo].[ParkingFacility](

[Id] [bigint] NOT NULL,

CONSTRAINT [PK_ParkingFacility] 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]

END

GO

SET ANSI_NULLS ON

GO

SET QUOTED_IDENTIFIER ON

GO

IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[ParkingFacility__To__Car_Lookup]') AND type in (N'U'))

BEGIN

CREATE TABLE [dbo].[ParkingFacility__To__Car_Lookup](

[Id] [bigint] NOT NULL,

[CarId] [bigint] NOT NULL,

[ParkingFacilityId] [bigint] NOT NULL,

CONSTRAINT [PK_ParkingFacility__To__Car_Lookup] 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]

END

GO

SET ANSI_NULLS ON

GO

SET QUOTED_IDENTIFIER ON

GO

IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[ParkingLot]') AND type in (N'U'))

BEGIN

CREATE TABLE [dbo].[ParkingLot](

[Id] [bigint] NOT NULL,

[Address] [nvarchar](50) NOT NULL,

CONSTRAINT [PK_ParkingLot] 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]

END

GO

SET ANSI_NULLS ON

GO

SET QUOTED_IDENTIFIER ON

GO

IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[ParkingGarage]') AND type in (N'U'))

BEGIN

CREATE TABLE [dbo].[ParkingGarage](

[Id] [bigint] NOT NULL,

[Address] [nvarchar](50) NOT NULL,

CONSTRAINT [PK_ParkingGarage] 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]

END

GO

IF NOT EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_ParkingFacility__To__Car_Lookup_Car]') AND parent_object_id = OBJECT_ID(N'[dbo].[ParkingFacility__To__Car_Lookup]'))

ALTER TABLE [dbo].[ParkingFacility__To__Car_Lookup] WITH CHECK ADD CONSTRAINT [FK_ParkingFacility__To__Car_Lookup_Car] FOREIGN KEY([CarId])

REFERENCES [dbo].[Car] ([Id])

GO

ALTER TABLE [dbo].[ParkingFacility__To__Car_Lookup] CHECK CONSTRAINT [FK_ParkingFacility__To__Car_Lookup_Car]

GO

IF NOT EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_ParkingFacility__To__Car_Lookup_ParkingFacility]') AND parent_object_id = OBJECT_ID(N'[dbo].[ParkingFacility__To__Car_Lookup]'))

ALTER TABLE [dbo].[ParkingFacility__To__Car_Lookup] WITH CHECK ADD CONSTRAINT [FK_ParkingFacility__To__Car_Lookup_ParkingFacility] FOREIGN KEY([ParkingFacilityId])

REFERENCES [dbo].[ParkingFacility] ([Id])

GO

ALTER TABLE [dbo].[ParkingFacility__To__Car_Lookup] CHECK CONSTRAINT [FK_ParkingFacility__To__Car_Lookup_ParkingFacility]

GO

IF NOT EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_ParkingLot_ParkingFacility]') AND parent_object_id = OBJECT_ID(N'[dbo].[ParkingLot]'))

ALTER TABLE [dbo].[ParkingLot] WITH CHECK ADD CONSTRAINT [FK_ParkingLot_ParkingFacility] FOREIGN KEY([Id])

REFERENCES [dbo].[ParkingFacility] ([Id])

GO

ALTER TABLE [dbo].[ParkingLot] CHECK CONSTRAINT [FK_ParkingLot_ParkingFacility]

GO

IF NOT EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_ParkingGarage_ParkingFacility]') AND parent_object_id = OBJECT_ID(N'[dbo].[ParkingGarage]'))

ALTER TABLE [dbo].[ParkingGarage] WITH CHECK ADD CONSTRAINT [FK_ParkingGarage_ParkingFacility] FOREIGN KEY([Id])

REFERENCES [dbo].[ParkingFacility] ([Id])

GO

ALTER TABLE [dbo].[ParkingGarage] CHECK CONSTRAINT [FK_ParkingGarage_ParkingFacility]

View 4 Replies View Related

Where Do The Contraints Live?

Mar 19, 2008

Can someone write for me an example query that would select all the constraints that are applied to specific table?

something like:

SELECT
FieldThatHasConstraint,
FieldTableName,
TableToWhitchThisFieldHasConstraint,
FieldOfTableToWhitchThisFieldHasConstraint
TypeOfConstraint
FROM
???
WHERE
TableThatIWantToSearchForConstraints='myTable'

View 4 Replies View Related

Instead-of Trigger And Contraints

Jul 23, 2005

Is Microsoft full of #*$#*% (again) or am I badly misunderstandingsomething?Quote from Microsoft's T-SQL doc:[color=blue]> INSTEAD OF triggers are executed instead of the triggering action.> These triggers are executed after the inserted and deleted tables> reflecting the changes to the base table are created, but before any> other actions are taken. They are executed before any constraints,[/color]^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^[color=blue]> so can perform preprocessing that supplements the constraint actions.[/color](SQL Server 2000 sp3a)CREATE TABLE t (a INT PRIMARY KEY,b CHAR(1) NOT NULL)I want to override the value of [b] with the value of 'X' wheninserting into t...CREATE TRIGGER t_tbi ON t INSTEAD OF INSERT AS BEGINSET NOCOUNT ONINSERT INTO t (a,b) (SELECT a,'X' FROM inserted)ENDLet's try it...INSERT INTO t (a,b) VALUES(1,'z')SELECT * FROM ta | b---|---1 | XGood, the trigger did what it was supposed to. Lets try aslight variation...INSERT INTO t (a) VALUES(2)Server: Msg 233, Level 16, State 2, Line 1The column 'b' in table 't' cannot be null.WTF? What was that I just read about "[instead-of triggers]are executed before any constraints"?!?!What's going on here???

View 8 Replies View Related

Sql Date Contraints

Jul 20, 2005

Hi,I was wondering how to do this.I have a table with two columns in design view (start date, end date).How do I set it within sql server (as constraint) or whatever that thestart date less than or equal to end date?Thanks:DHRUV

View 5 Replies View Related

Overriding ForeignKey Constraints Under Certain Conditions To Perform CASCADE DELETE

Jun 5, 2008

Hi,
We have a DB with a heirarchy of tables each connected via Guids and controlled for Delete Operations by Foreign Key Constraints. However, under certain privileged conditions we would like CERTAIN users to be able to perform a Cascade Delete all the way down.
Thus by example we have tables A,B,C,D - Typically once a record is inserted into Table A then we can add multiple records in Table B referencing that new record in Table A...and so on through records in Table C referencing Table B...records in Table D referencing table C. Now when we try and delete that ONE Record in Table A we 'could' implement CASCADE DELETES which would delete all those records in Table B,C,D.
We decided that was too dangerous to implement as Whooosh....all records could be deleted by a non-privileged user deleteing that ONE records in Table A, so we changed the Cascade DELETE to NO ACTION. However, there are times (hah...particularly in Testing !) when we would like a privilegd user to be able to DO that task...i.e. perform a CASCADE delete.
Has anybody got any suggestions on how this would be best, easily and securely implemented.
I have had a brief look at INSTEAD OF Triggers but am not sure about the pitfalls of using this...
ANy help appreciated,
 Cheers,
Desmond. 
 
 
 

View 2 Replies View Related

Relations Between Tables - Contraints Diagram

May 4, 2004

Hi all,
I have a big problem. I have many tables with constraints, with foreign keys. I need to create a ordered list of tables, on the top must be the basic table what has no parents, then the second level tables (those depends on the first level) the the names of third level etc.

for example:
Table A[id]
Table B[id, idc]
Table C[id, ida]
Table D[id, ida]
Table E[id, idc]

I tried it by using information_scheme but I was unsuccesfull.

The result should be:
A
C
D
B
E

Thank you,
Tom.

View 2 Replies View Related

Loading Tables With Foriegn Key Contraints

Aug 31, 2006

Hi,

I am having trouble loading tables (within the same data flow) that have a foriegn key relationship defined between them. For instance:

Table A is a parent (one side of the relationship) to Table B (many side of the relationship).

I am trying to load Table A first within the data flow and then Table B after, but I get the following error:

[OCMD EntityRole Insert [2666]] Error: An OLE DB error has occurred. Error code: 0x80040E2F. An OLE DB record is available. Source: "Microsoft SQL Native Client" Hresult: 0x80040E2F Description: "The statement has been terminated.". An OLE DB record is available. Source: "Microsoft SQL Native Client" Hresult: 0x80040E2F Description: "The INSERT statement conflicted with the FOREIGN KEY constraint "FK_EntityRole_Entity". The conflict occurred in database "ODS", table "dbo.Entity", column 'EntityGuid'.".

I am currently using OLE DB commands to perform the inserts, I load table A and move on to then load Table B, I can see the records in Table A before trying to load Table B but for some reason Table B load still fails.

I was thinking maybe this has something to do with the transaction setting or Isolation level but have played with this to no avail (currently everything is the default - supported/serializable). Also, I am thinking maybe because the OLE DB commands are creating two seperate connections (they are using the same connection manager) the second one is unable to see the transactions from the other (first) connection (Table A)?

Is there a way around this without dropping (disabling) forigen keys before the load and adding them back in after? Would like to avoid this?

I would also like to avoid reading the data source multiple times. Everything I need is in the one source so I would like to populate multiple tables from the one source data stream instead of reading the same data 2,3 or 4 times etc.

Seems to me there must be a simple explanation/solution for this but I'm stuck at this point?

P.S.

I was intially using OLE DB destinations (because they are much faster) and was having the same issue, which made sense because the OLE DB destinations do not let you pass the data stream on so I had to multi cast to the destinations so they were loading at the same time. I would rather use the OLE DB destinations so if you have any ideas around how I could do this using those components that would be appreciated too!

Thanks!

View 3 Replies View Related

Merge Replication And Unique Contraints

Jan 26, 2006

Hi,

I have a slight problem which I'm sure must be a common happening. Here's my problem.

I'm using Merge replication and I have a table the has a unique contraint on a non primary key column (the column is called [name]). The thing that goes wrong (for me) is that when a new record is added in a subscriber and a new record is added in the publisher before a synchronization and both records have the same [name] value then when the merge agent runs I get an unresolved conflict because of a unique index violation.

I've read the BOL and I'm left thinking that in order to solve this problem then I must use a custom resolver. Is this the best way of handling such a conflict? Actually if it is I'm still a little stuck as I'm not sure what I could do to help the situation inside the custom resolver anyway!!

Any help would be much appreciated.

Thanks

Graham

View 3 Replies View Related

Cascade Delete Contraints - Accessible Through TSQL?

Sep 25, 2006

Hi all,

I was wondering if there is an easy way to loop through all contraints in a database and programmatically set the cascade delete to ON. I have a database with hundreds of contraints, so individually setting cascade delete on them is not optimal.

Thanks for any info in advance!

 

I think that the constraints are simply held in one of the system datatables, is there anyway to simply update that table?

 

 

 

View 3 Replies View Related

Delete/truncate Table Ignoring Contraints

Aug 23, 2006

Is there any easy way to truncate a table which has a foreign key restraint? I want to override the default behavior which is to not allow truncate of parent tables. I want to be able to temperarily remove the contraint so I can truncate the temple, how do you do this?

View 6 Replies View Related

Review Of DB Design - Normalized, Contraints, Foreign Keys, Etc.

Jul 2, 2004

First of all, this is my initial thread here on dbforums. I come from the land of Broadband Reports and would like to say, Hello fellow DB enthusiasts. :)

I'm not a novice to relational databases (Access MDBs), but new to implementing a db via SQL SERVER (2000 in this case) and using Access Data Projects.

My partial db schema is as follows:

participants
---DID (pk) char(1)
---LID (fk - schools) char(4)
---studentLast varchar(50)
---studentFirst varchar(25)

Sample Data would be
010191M001 | 5671 | SPARKS | JONATHAN
030495F283 | 5671 | DYLAN | CYNTHIA
=====================================

enrollhist (insert/update trigger for enrollactive)
---EID (pk - autonumber) bigint(8)
---EMID (fk - enrollmode) int(4)
---DID (fk - participants) char(10)
---LID (fk - schools) char(4)
---enrollactive bit(1)

Sample Data would be
38173 | 4 | 030495F283 | 9003 | 0
38266 | 3 | 010191M001 | 5671 | 0
39022 | 6 | 030495F283 | 9003 | 0
39036 | 5 | 030495F283 | 9003 | 0
39044 | 4 | 030495F283 | 5671 | 1
39117 | 4 | 010191M001 | 5671 | 1
=====================================

enrollmode
---EMID (pk) int(4)
---mode varchar(25)

Sample Data would be
1 | RECEIVED
2 | WAITING
3 | PENDING
4 | ENROLLED
5 | DROPPED
6 | TRANSFERRED
10 | ORPHANED
11 | DENIED
=====================================

schools
---LID (pk) varchar(4)
---CTID (fk - caltracks) char(1)
---AID (fk - agencies) char(1)
---SDID (fk - schooldist) char(1)
---COID (fk - countydist) char(1)
---sitename varchar(25)
---sitetitle varchar(75)

Sample Data would be
5671 | 3 | 2 | 1 | 4 | ASCOT | ASCOT AVENUE
9003 | 2 | 1 | 4 | 1 | ROWAN | ROWAN AVENUE
2865 | 1 | 3 | 2 | 3 | BRIGHT | BIRDELEE BRIGHT
=====================================

caltracks
---CTID (pk) char(1)
---legend char(4)
---trktitle varchar(15)
---trkcnt int(4)

Sample Data would be
1 | 9030 | 90/30 | 4
2 | CON6 | CONCEPT-6 | 3
3 | SNGL | SINGLE TRACK | 1
=====================================

agencies
---AID (pk) char(1)
---legend varchar(4)
---agencytitle varvhar(50)

Sample Data would be
1 | CRYS | CRYSTAL STAIRS
2 | MAOF | MEXICAN AMERICAN FOUNDATION
3 | PATH | PATHWAYS
4 | CCRC | CHILD CARE RESOURCE CENTER
5 | CHSC | CHILDREN'S HOME SOCIETY OF CALIFORNIA
==========================================

THE REMAINING "FKs" FROM SCHOOL ARE SIMILAR, as is other tables and their relationships. The design of the foreign keys were made using sql and the keyword "REFERENCES" and "FOREIGN KEY."

My questions are: :confused:
(1) Is the use of FK as a Constraint any different than using an INDEX and how?
(2) Should I Alter the Tables to include CASCADING Up/Down?
(3) Are the use of CHARs Ok for the Keys?
(4) Have I over/under-normalized any of the relationships?

View 4 Replies View Related

Is A Foreignkey Column Can Refer Two Primarykey Column From Two Different Tables?

May 13, 2008

Hi,


I need to create a table (Named as C) with a foreignkey column. That column should references with a primarykey column in table A and a primarykey column in table B. Is this possible?

Thanks in advance.

ramesh.p

View 1 Replies View Related







Copyrights 2005-15 www.BigResource.com, All rights reserved