Finding all table and fields that are involved in a one to many relation (on many side) with a given field

Hi,

I have a master table, and several other tables that are related to
this master through one to many relations.
How can I find all tables and fields which are in relation with the
primary key in the master table, on "many" side?

I know I can extract this by querying views from INFORMATION_SCHEMA,
but I don't know where exactly I can find this info

Thank you
0
bz
6/11/2010 6:59:20 PM
sqlserver.programming 1873 articles. 0 followers. Follow

4 Replies
1021 Views

Similar Articles

[PageSpeed] 36

One way

Select op.name As ParentTableName, oc.name As ChildTableName, c.name As 
ChildColumnName
From sys.foreign_key_columns kc
Inner Join sys.objects op On kc.parent_object_id = op.object_id
Inner Join sys.objects oc On kc.referenced_object_id = oc.object_id
Inner Join sys.columns c On kc.referenced_object_id = c.object_id And 
kc.referenced_column_id = c.column_id
Order By op.name, oc.name, kc.constraint_column_id;

Tom

"bz" <bzamfir@gmail.com> wrote in message 
news:26a6f2dc-4ccc-47d2-af23-63a037f78c5c@c33g2000yqm.googlegroups.com...
> Hi,
>
> I have a master table, and several other tables that are related to
> this master through one to many relations.
> How can I find all tables and fields which are in relation with the
> primary key in the master table, on "many" side?
>
> I know I can extract this by querying views from INFORMATION_SCHEMA,
> but I don't know where exactly I can find this info
>
> Thank you 

0
Tom
6/11/2010 7:44:14 PM
Thank you.

I changed the query to better match what I need as follows:

SELECT     TOP (100) PERCENT TableParent.name AS ParentTableName,
ColumnParent.name AS ParentColumnName, TableChild.name AS
ChildTableName,
                      ColumnChild.name AS ChildColumnName
FROM         sys.foreign_key_columns AS kc INNER JOIN
                      sys.objects AS TableChild ON kc.parent_object_id
= TableChild.object_id INNER JOIN
                      sys.objects AS TableParent ON
kc.referenced_object_id = TableParent.object_id INNER JOIN
                      sys.columns AS ColumnParent ON
kc.referenced_object_id = ColumnParent.object_id AND
kc.referenced_column_id = ColumnParent.column_id INNER JOIN
                      sys.columns AS ColumnChild ON
kc.parent_object_id = ColumnChild.object_id AND kc.parent_column_id =
ColumnChild.column_id
ORDER BY ParentTableName, ChildTableName, kc.constraint_column_id

Reason is, I need to know also the parent field (since I need to
perform some operations on every child table / field based on master
table / field) and changed the naming to have Parent* on the on
"primary key" side of the relation and child on "foreign key" side

Thanks again



On 11 iun., 22:44, "Tom Cooper" <tomcoo...@comcast.net> wrote:
> One way
>
> Select op.name As ParentTableName, oc.name As ChildTableName, c.name As
> ChildColumnName
> From sys.foreign_key_columns kc
> Inner Join sys.objects op On kc.parent_object_id = op.object_id
> Inner Join sys.objects oc On kc.referenced_object_id = oc.object_id
> Inner Join sys.columns c On kc.referenced_object_id = c.object_id And
> kc.referenced_column_id = c.column_id
> Order By op.name, oc.name, kc.constraint_column_id;
>
> Tom
>
> "bz" <bzam...@gmail.com> wrote in message
>
> news:26a6f2dc-4ccc-47d2-af23-63a037f78c5c@c33g2000yqm.googlegroups.com...
>
> > Hi,
>
> > I have a master table, and several other tables that are related to
> > this master through one to many relations.
> > How can I find all tables and fields which are in relation with the
> > primary key in the master table, on "many" side?
>
> > I know I can extract this by querying views from INFORMATION_SCHEMA,
> > but I don't know where exactly I can find this info
>
> > Thank you

0
bz
6/12/2010 10:08:55 AM
Actually, since my tables are in various schemas, I change the query
to include the schema name for both master and chiuld tables, as
below:

SELECT     TOP (100) PERCENT SchemaParent.name AS ParentSchemaName,
TableParent.name AS ParentTableName, ColumnParent.name AS
ParentColumnName,
                      SchemaChild.name AS ChildSchemaName,
TableChild.name AS ChildTableName, ColumnChild.name AS ChildColumnName
FROM         sys.foreign_key_columns AS kc INNER JOIN
                      sys.objects AS TableChild ON kc.parent_object_id
=3D TableChild.object_id INNER JOIN
                      sys.schemas AS SchemaChild ON
TableChild.schema_id =3D SchemaChild.schema_id INNER JOIN
                      sys.objects AS TableParent ON
kc.referenced_object_id =3D TableParent.object_id INNER JOIN
                      sys.schemas AS SchemaParent ON
TableParent.schema_id =3D SchemaParent.schema_id INNER JOIN
                      sys.columns AS ColumnParent ON
kc.referenced_object_id =3D ColumnParent.object_id AND
kc.referenced_column_id =3D ColumnParent.column_id INNER JOIN
                      sys.columns AS ColumnChild ON
kc.parent_object_id =3D ColumnChild.object_id AND kc.parent_column_id =3D
ColumnChild.column_id
ORDER BY ParentTableName, ChildTableName, kc.constraint_column_id

On 12 iun., 13:08, bz <bzam...@gmail.com> wrote:
> Thank you.
>
> I changed the query to better match what I need as follows:
>
> SELECT =A0 =A0 TOP (100) PERCENT TableParent.name AS ParentTableName,
> ColumnParent.name AS ParentColumnName, TableChild.name AS
> ChildTableName,
> =A0 =A0 =A0 =A0 =A0 =A0 =A0 =A0 =A0 =A0 =A0 ColumnChild.name AS ChildColu=
mnName
> FROM =A0 =A0 =A0 =A0 sys.foreign_key_columns AS kc INNER JOIN
> =A0 =A0 =A0 =A0 =A0 =A0 =A0 =A0 =A0 =A0 =A0 sys.objects AS TableChild ON =
kc.parent_object_id
> =3D TableChild.object_id INNER JOIN
> =A0 =A0 =A0 =A0 =A0 =A0 =A0 =A0 =A0 =A0 =A0 sys.objects AS TableParent ON
> kc.referenced_object_id =3D TableParent.object_id INNER JOIN
> =A0 =A0 =A0 =A0 =A0 =A0 =A0 =A0 =A0 =A0 =A0 sys.columns AS ColumnParent O=
N
> kc.referenced_object_id =3D ColumnParent.object_id AND
> kc.referenced_column_id =3D ColumnParent.column_id INNER JOIN
> =A0 =A0 =A0 =A0 =A0 =A0 =A0 =A0 =A0 =A0 =A0 sys.columns AS ColumnChild ON
> kc.parent_object_id =3D ColumnChild.object_id AND kc.parent_column_id =3D
> ColumnChild.column_id
> ORDER BY ParentTableName, ChildTableName, kc.constraint_column_id
>
> Reason is, I need to know also the parent field (since I need to
> perform some operations on every child table / field based on master
> table / field) and changed the naming to have Parent* on the on
> "primary key" side of the relation and child on "foreign key" side
>
> Thanks again
>
> On 11 iun., 22:44, "Tom Cooper" <tomcoo...@comcast.net> wrote:
>
> > One way
>
> > Select op.name As ParentTableName, oc.name As ChildTableName, c.name As
> > ChildColumnName
> > From sys.foreign_key_columns kc
> > Inner Join sys.objects op On kc.parent_object_id =3D op.object_id
> > Inner Join sys.objects oc On kc.referenced_object_id =3D oc.object_id
> > Inner Join sys.columns c On kc.referenced_object_id =3D c.object_id And
> > kc.referenced_column_id =3D c.column_id
> > Order By op.name, oc.name, kc.constraint_column_id;
>
> > Tom
>
> > "bz" <bzam...@gmail.com> wrote in message
>
> >news:26a6f2dc-4ccc-47d2-af23-63a037f78c5c@c33g2000yqm.googlegroups.com..=
..
>
> > > Hi,
>
> > > I have a master table, and several other tables that are related to
> > > this master through one to many relations.
> > > How can I find all tables and fields which are in relation with the
> > > primary key in the master table, on "many" side?
>
> > > I know I can extract this by querying views from INFORMATION_SCHEMA,
> > > but I don't know where exactly I can find this info
>
> > > Thank you

0
bz
6/12/2010 10:39:00 AM
Here is a query that will match foreign keys with primary/unique keys
and pull related info:

SELECT C.TABLE_CATALOG,
       C.TABLE_SCHEMA,
       C.TABLE_NAME,
       C.COLUMN_NAME,
       X.CONSTRAINT_NAME AS FK,
       X.UNIQUE_CONSTRAINT_NAME AS PK,
       P.TABLE_NAME AS PK_TABLE,
       P.COLUMN_NAME AS PK_COLUMN,
       K.CONSTRAINT_NAME AS PK_COLUMN_CONSTRAINT
FROM INFORMATION_SCHEMA.COLUMNS AS C
JOIN INFORMATION_SCHEMA.TABLES AS T
  ON C.TABLE_CATALOG = T.TABLE_CATALOG
 AND C.TABLE_SCHEMA = T.TABLE_SCHEMA
 AND C.TABLE_NAME = T.TABLE_NAME
LEFT JOIN (SELECT U.TABLE_CATALOG,
                  U.TABLE_SCHEMA,
                  U.TABLE_NAME,
                  U.COLUMN_NAME,
                  U.ORDINAL_POSITION,
                  R.CONSTRAINT_CATALOG,
                  R.CONSTRAINT_SCHEMA,
                  R.CONSTRAINT_NAME,
                  R.UNIQUE_CONSTRAINT_CATALOG,
                  R.UNIQUE_CONSTRAINT_SCHEMA,
                  R.UNIQUE_CONSTRAINT_NAME
           FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE AS U
           JOIN INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS AS R
             ON U.CONSTRAINT_CATALOG = R.CONSTRAINT_CATALOG
            AND U.CONSTRAINT_SCHEMA = R.CONSTRAINT_SCHEMA
            AND U.CONSTRAINT_NAME = R.CONSTRAINT_NAME) AS X
  ON C.TABLE_CATALOG = X.TABLE_CATALOG
 AND C.TABLE_SCHEMA = X.TABLE_SCHEMA
 AND C.TABLE_NAME = X.TABLE_NAME
 AND C.COLUMN_NAME = X.COLUMN_NAME
LEFT JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE AS P
  ON X.UNIQUE_CONSTRAINT_CATALOG = P.CONSTRAINT_CATALOG
 AND X.UNIQUE_CONSTRAINT_SCHEMA = P.CONSTRAINT_SCHEMA
 AND X.UNIQUE_CONSTRAINT_NAME = P.CONSTRAINT_NAME
 AND X.ORDINAL_POSITION = P.ORDINAL_POSITION
LEFT JOIN (SELECT A.CONSTRAINT_CATALOG,
                  A.CONSTRAINT_SCHEMA,
                  A.CONSTRAINT_NAME,
                  A.TABLE_NAME,
                  A.COLUMN_NAME
           FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE AS A
           JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS AS B
             ON A.CONSTRAINT_CATALOG = B.CONSTRAINT_CATALOG
            AND A.CONSTRAINT_SCHEMA = B.CONSTRAINT_SCHEMA
            AND A.CONSTRAINT_NAME = B.CONSTRAINT_NAME
            AND B.CONSTRAINT_TYPE = 'PRIMARY KEY') AS K
  ON C.TABLE_CATALOG = K.CONSTRAINT_CATALOG
 AND C.TABLE_SCHEMA = K.CONSTRAINT_SCHEMA
 AND C.TABLE_NAME = K.TABLE_NAME
 AND C.COLUMN_NAME = K.COLUMN_NAME
WHERE T.TABLE_TYPE = 'BASE TABLE';

-- 
Plamen Ratchev
http://www.SQLStudio.com
0
Plamen
6/13/2010 3:12:38 AM
Reply:

Similar Artilces:

A code to import other xls data into one xls file
Hi there. Can anyone help me in creating a VB code in excel Module that imports data like file name;direct cost; and year from several xls spreadsheets [reports_1, reports_2, ...] (from different sheets and cells) into one spreadsheet [summary] into the following columns accordingly: (column 1 [file name]: file name; column 2 [direct cost]: dollar amounts, column 3 [year]: year)? i already have the code that pulls file names from the folder directory and pastes the data into column 1 [file name]. may be it will be easier to have the code refer to that column 1. Please note that t...

I need to compare 3 numbers and find the one in the middle
I have three numbers in a single row and would like to identify the middle number enter that number in another cell. Example: 1st # 2nd # 3rd # result 628 678 720 678 655 625 700 655 748 720 725 725 is there a function in excel that can do this? Thanks, Eddie Try =LARGE(A1:C1,2) VBA Noo -- VBA Noo ----------------------------------------------------------------------- VBA Noob's Profile: http://www.excelforum.com/member.php?action=getinfo&userid=3383 View this thread: http://www.excelforum.com/showthread.php?threadid=56811 fasteddie wrote.....

Find Duplicate names and delate
Dear experts, I have a small doubt could you clarify that??? That is I find duplicate name but I want to delete one name only, if I filter DUPLICATE….. both names are showing… 1. Select the range of data including the header. You need to have headers for these columns 2. From menu Data>Filter>Advanced Filter>Copy to another location 3. In 'copy to' specify the target cell and check 'Unique records only' 4. Click OK will give you the unique list -- Jacob "Find Duplicate names and delate" wrote: > Dear experts, > I have a small ...

Finding a Median
I'm trying to write a query that will return a median for various values taken from a previous query. I've seen some suggestions in my searching, but I haven't been able to get them working. They are also all from before 2003 and refer to Access 97 and 2000. Has any functionality been added to 2003 for this? Or is there a non- code-based way to do it? I've seen it suggested to write a code to open the query, sort it, find the total number of records, divide it in half, then seek out the middle record using that value. I'm still very green when it comes to code, though...

Find a Value the first Time It Occurs
I have a row of values that shows the total cumulative number of sales of items by month. Occasionally, there may be no sales in a month for an item so the cumulative value would stay the same for more than one month. I want to select a number in the row the first time it occurs and not select it if it repeats. What are you wanting to do with the info? To return position (column number) of number 1234 within row 2: =MATCH(1234,2:2,0) A formula that signals it's the first occurence: =COUNTIF($A2:A2,A2)=1 This could be used in a helper row, or as a conditional format f...

Find/Replace in RichEdit 2.0
I'm using Windows ME and I've switched from RichEdit 1.0 to 2.0 for my CRichEditDoc/View application so that I can use the ITextDocument interface and can do things such as suspend/resume the Redo buffer. Problem is, now the Find/Replace dialogs don't seem to do anything. If I revert back to RichEdit 1.0 they do! What's going on? BUMP! adriangibbons@yahoo.co.uk (Adrian Gibbons) wrote in message news:<34a2acd5.0404130713.123dbaab@posting.google.com>... > I'm using Windows ME and I've switched from RichEdit 1.0 to 2.0 for my > CRichEditDoc/View application...

setting the same choice and order of the fields in all the folders
This is a multi-part message in MIME format. ------=_NextPart_000_0008_01C422DC.8D05E5E0 Content-Type: text/plain; charset="koi8-r" Content-Transfer-Encoding: quoted-printable How do I set the same choice and order of the fields in all the folders? For the moment the View settings apply to a particular folder and I have = to set them manually in every folder. ------=_NextPart_000_0008_01C422DC.8D05E5E0 Content-Type: text/html; charset="koi8-r" Content-Transfer-Encoding: quoted-printable <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> <...

query a table and subform
Help, I have 3 tables 1. Printer table: printerID, ModelID, SerialNum, MACAdd 2. Toner table: TonerID, ModelID, PartName 3. Invoice table: InvoiceID, Date, Qty, PrinterID, TonerID How can I pull up toners based on the printerID in Invoice table? I set the TonerID as a combo box, Could anyone help me with the query that i need. The inovoice table actual is a subform under printer in the Form. so when I choose the printer from the main form the subform printerID changes accordingly, I just don't know how to generate a list of toner for user to choose based on the printer or m...

Replacing data in Pivot Table causes Field name change
Good morning, I have a pivot table report that uses about 1200 rows of data on a neighboring page. Today I produced new monthly data and pasted it on top of the old data. When I do this the report's left most column field names all change from FieldName to FieldName2. When I look in the drop down box for that field it seems to have duplicated the fields when I pasted the new data. I'm able to work around it by changing the displayed lables from FieldName2 to FieldName"space""space". I can't change to just FieldName because that is already in use. M...

OK, a really tricky one now for Excel gurus!
A perfect response before, this time a little trickier! I have two data sources: Data A) a column of approx. 3000 cells featuring the 'Post Code' only from a database of addresses. Data B) The Australian postcode database as found and downloaded from the below link: http://www1.auspost.com.au/postcodes/index.asp?sub=2 What I want to happen is each postcode from source 'A' to match up with the corresponding post code from source 'B' (this is in column A). Once it matches, the 'Delivery Office' (column E) is to appear in column B of Data Source Sheet A......

Find (but not find)
My program takes a name from sheet3 goes to sheet1 to Find the name. If it cannot find name, how do you do an If/End to Exit Do while or find out if name has been founf? I have "On Error Resume Next" in program. Thanks again for all your help Gordon As ALWAYS, post your code for comments & suggestions. -- Don Guillett Microsoft MVP Excel SalesAid Software dguillett1@austin.rr.com "Gordon" <gwelch1938@yahoo.com> wrote in message news:1184612089.486737.144020@n60g2000hse.googlegroups.com... > My program takes a name from sheet3 goes to sheet1 to Find the na...

Linking tables together
I have set up five tables in my database but now I want to merge the tables into one table. How do I do that? If all the tables have identical structures, you can use a union query. Select * from tbl1 Union Select * from tbl2 Union Select * from tbl3 ..... "Maggie" <schmidt.margaret@gmail.com> wrote in message news:266ff9f6-f9b8-4f77-88ea-358518bfc936@q77g2000hsh.googlegroups.com... >I have set up five tables in my database but now I want to merge the > tables into one table. How do I do that? You are best not to. The information in the tables will refer to a sp...

Finding an event
Hello, I am developing an app that uses a single worksheet to enter data. When user double clicks a button, a new window (in same workbook) opens with a new sheet. My problem is that excel does not seem to have any events for close of window if there are multiple windows in a workbook. Can someone help Peter Peter, That triggers the Workbook_WindowActivate event, you can use that. HTH Bob "Peter Ostermann" wrote in message news:i9m5v8$7bv$02$1@news.t-online.com... Hello, I am developing an app that uses a single worksheet to enter data. When user double clicks a button...

Table Row Height and Column Width
Is there a way to exactly set the row height and column width in Publisher 2003? For instance, I want all the rows to be .25 inches high or 16 points high -- can I set this? No... You could create ruler guides. Right-click a ruler guide, click format ruler guides. You then can adjust your table rows by snapping to the guides. -- Mary Sauer http://msauer.mvps.org/ "Lori T" <Lori T@discussions.microsoft.com> wrote in message news:2631297F-839A-4699-B4F6-45601B771E1A@microsoft.com... > Is there a way to exactly set the row height and column width in Publisher > 2003...

Find value in a column and insert rows above
The set up looks like this: ColU ColV ColW ColX Y N N N Y N N N N Y N N N N Y N N N Y N N N Y N N N Y N N N Y Y Columns will always be U through X and will always be sorted in this order. I need to find the first Y in each column and insert 2 rows above that row. On the blank row above the first Y, I need to highlight in yellow and put title in the first cell, such as New, Old, Existing, Deleted. Any help would be greatly appreciated. Thanks for your time, Dee If desired, send your file to my address below. I will only look if: 1. You send a copy of this ...

League table #3
I'm trying to put a football league table together, which i'd like to include: the team, matches played, won, drawn, lossed, goals for, goals against, goal difference and points. i've pretty much done most of it but my main two problems are when there's no score entered for each match it enters in the table as a draw and my other issue is once a score is entered i can't get the teams to move up and down the league automatically. is there a way to lock the formulas for each team when they move up and down Please help my email is Regard S Hi S, A couple of general observ...

Criteria to prompt for field and omit certain records
I have a query that prompts the user for the install number. I also need it to omit any records that have "obsolete" in any of the revision fields. Following is my SQL code. If I include the Not Like "*obs*" criteria, the install number is not included in the report. If I exclude the Not Like "*obs*" criteria, the install number is included in the report, however all records with a revision of Obsolete also show up. SELECT [Engineering Drawing Numbers].MasterProject, [Engineering Drawing Numbers].[INSTALL NUMBER], [Engineering Drawing Numbers].[INST...

Pivot table Options
I have a daily file. Column A is a manufacturer (multiple) , column B is model (multiple), Column C is machine number (unique). Other columns show types of activity for a total of ~10K records per day. But only about 40 make/model groups with 1000 unique instances. I would like to use a pivot table to determine how many models of each machine are in use each day. Is it possible to use a pivot table to count unique records of each Make/model? The current macro uses Sumproduct to identify unique records and then counts each make/model combo with sumif. I am looking for a faster o...

How do I print 4 different postcards on one sheet in Publisher
Our company sends postcards to customers everytime their properties are advertised in the newspaper. There is usually 8 different properties advertised a day. The templet is the same everytime as far as the design of the card. What is different is the description on each and the picture. Currently we are having to print 4 of each card, each day. This works fine as long as there is not a change in the wording of the ad the next time it is ran or a price change. This is getting to be confusing, wasteful and causing mistakes. I have tried to read about mail merge but this doesn't...

cannot find database
I have an excel spreadsheet that is supposed to update a access db. Whenever I try to save the .xls I get an error stating cannot find db. Even when I open the db with access, I get the error and the db opens anyway?????? This only happens on 2 out of 20 pc's and I cannot figure out why???????? Thanks ...

Sum if Condition is Equal in Range Date and find column
I want to make a sum if Range is a week number and if style is Equal to CONC-92 or CONC-45 Week# 49 Week# 50 CONC-92= 27 CONC-92= 30 CONC-45= 27 CONC-45= 30 Datas are in a pivot table and... Pivot table looks like this: Date CONC-92 CONC-45 CONC-92 CONC-45 12/7 5 5 10 10 12/8 2 2 10 10 12/9 5 5 10 10 12/10 5 5 10 10 please help -- Lorenzo Díaz Cad Technician ...

Trapping a NO FIND after a find
I use the code below to store a row number to a variable after a find. I would like to trap a NO FIND if the find is unsuccessfull Any ideas. FSt1 provided the code below Sub macfindrow() dim rn as string dim rng as range dim therow as long rn = inputbox("enter something to find") if rn <> "" then Set rng = nothing Set rng = range("A1:IV65536").Find(what:=rn, _ After:=Range("A1"), _ Lookin:=xlformulas, _ Lookat:=xlpart, _ ...

Trying to collapse a table, what Function should I use?
I have a table of data (numbers) which is 70 rows by 21 columns, which I would like to summarize into a 5 x 3 table. So every 14 rows by 7 columns sums into a single cell on another worksheet. My original table would be like 1 2 3 ... 20 21 1 2 .... 69 70 and my summary table would be 01-07 08-14 15-21 01-14 A B C 15-28 D E F 29-42 G H I 43-56 J K L 57-70 M N O where A = sum of all numbers in the intersection of rows 1-14 and columns 1-7 where O = sum of all numbers...

How do I find the out of office reply?
My out of office reply is missing from tools. How can I retrieve it? Out of Office reply <Out of Office reply@discussions.microsoft.com> wrote: > My out of office reply is missing from tools. How can I retrieve it? Unless you are using an Exchange server, you will not have the Out of Office Assistant. See this: http://www.slipstick.com/rules/autoreply.htm -- Brian Tillman ...

Finding numbers in rows and highlighting them
Hi everybody :) I need help. This is a lotto system. I have a spreadsheet with 508 rows and 45 columns. In each row there are 45 numbers mixed (1 to 45). I need a script or some other way to find where particular (drawn) numbers are in each of the 508 rows. If my explanation is not clear please ask for farther clarification. Thank you in advance for your help. Joh -- Johncobb4 ----------------------------------------------------------------------- Johncobb45's Profile: http://www.excelforum.com/member.php?action=getinfo&userid=1658 View this thread: http://www.excelforum.com/showt...