Getting primary/foreign keys and referenced tables and columns

OK, I've been wrestling with this for a while; time to ask for help.

I need a query (SQL 2005/2008) that, given a table name, will return the 
column information for that table as shown in SSMS (schema name, table name, 
column name, if it's a primary or foreign key; AND, additionally, if it is a 
foreign key - the referenced table and column that contains the primary 
key).

I have been able to put together a query to get primary keys and one to get 
the foreign keys, but unable to pull it all together with the inclusion of 
the reference information for foreign keys! Any help?

Thanks! 

0
omnistead
12/18/2009 7:17:42 PM
sqlserver.programming 1873 articles. 0 followers. Follow

2 Replies
677 Views

Similar Articles

[PageSpeed] 36

Select  s.name As SchemaName,
  t.name As TableName,
  c.name As ColumnName,
  Case When ic.index_id Is Null Then 'No' Else 'Yes' End As InPrimaryKey,
  Object_Name(c2.object_id) As ReferencedTable,
  c2.name As ReferencedColumn
From sys.tables t
Inner Join sys.schemas s On t.schema_id = s.schema_id
Inner Join sys.columns c On t.object_id = c.object_id
Left Join sys.indexes i On t.object_id = i.object_id And i.is_primary_key = 
1
Left Join sys.index_columns ic On t.object_id = ic.object_id And c.column_id 
= ic.column_id And i.index_id = ic.index_id
Left Join sys.foreign_key_columns fkc On t.object_id = fkc.parent_object_id 
And c.column_id = fkc.parent_column_id
Left Join sys.columns c2 On fkc.referenced_object_id = c2.object_id And 
fkc.referenced_column_id = c2.column_id
Where t.name = 'Product'
Order By s.name, c.column_id;

Tom

"omnistead" <mhunt5@hotmail.com> wrote in message 
news:eWGpVbBgKHA.3552@TK2MSFTNGP06.phx.gbl...
> OK, I've been wrestling with this for a while; time to ask for help.
>
> I need a query (SQL 2005/2008) that, given a table name, will return the 
> column information for that table as shown in SSMS (schema name, table 
> name, column name, if it's a primary or foreign key; AND, additionally, if 
> it is a foreign key - the referenced table and column that contains the 
> primary key).
>
> I have been able to put together a query to get primary keys and one to 
> get the foreign keys, but unable to pull it all together with the 
> inclusion of the reference information for foreign keys! Any help?
>
> Thanks! 

0
Tom
12/18/2009 8:43:50 PM
Here is a query that is probably a bit too complex but uses the information schema views which supposedly will work 
across different versions (you just need to add a predicate for table name in the WHERE clause as currently it pulls all 
tables in the current database):

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
12/18/2009 10:34:45 PM
Reply:

Similar Artilces:

VLookup to Hide Columns
Hi everyone - I'm still trying to figure out how to perform this one. Within my Timesheet tool, I use a VLookup table, on a data entry page, that contains employee names, departments, etc...... Also on the data entry page, are a number of columns (designated with specific housing programs) where the employee enters their daily hours depending on which program they work in. The thing is that certain employees only work in certain programs where it would be easier if the program columns that the employee does not deal with will "hide" once the employee chooses their names from th...

i get error 404 not found when trying to download
I'm trying to download nokia pc suite to windows xp to upload gallery onto the computer but get error message404 not found - how can i download this pc suite please -- Krysy Albutt Krysy Albutt wrote: > I'm trying to download nokia pc suite to windows xp to upload gallery > onto the computer but get error message404 not found - how can i > download this pc suite please Care to enlighten us how this pertains to: - 1) Microsoft 2) Publisher 3) Windows If you're having problems downloading from the *NOKIA* site where do you think you should be directing your ...

Q: How to automatically adapt column width with XML format?
Hi. I'm developing an application that outputs its results to an XML file (with Excel XP's DTD). The trouble is the column width, which is set at default. Is there an XML tag which allow to adapt width automatically? I thought about a VBA macro, but I noticed that VBA code isn't stored in XML Excel's files. Thanks in advance, Francesco. ...

How to get Calendar to send me reminders
I have changed my e-mail address but for some reason I cannot get Calendar to send reminders to my new address - I think I have carried out all that is necessary to effect the changover but I am not getting reminders sent. Can anyone help please? Is the Calendar Live ID based and accessible at Calendar.live.com ? -- ....winston ms-mvp mail "Dabardevon" wrote in message = news:FDC2B3B2-EDE4-41B1-BFC4-C0F9ED59CFB9@microsoft.com... I have changed my e-mail address but for some reason I cannot get = Calendar to send reminders to my new address - I think I have...

Some recipients get the attachment, some get winmail.dat
This one has me baffled. We are using Exchange 2000 and Outlook 2000 and have been for 8 months. No previous problems with attachments (.doc, .xls, .jpg). About 2 weeks ago, we started hearing from certain recipients that the attachment wasn't arriving; instead they were getting an unreadable file called winmail.dat. MS says that this is because the sender is using Rich Text to format the email. We have changed the senders to use Plain Text and still have the same problem. If the email is sent to several recipients, some will get the attachment fine, some will not. This didn'...

Likert scale calculation
I have used the following table in my survey: Frequency of use - check which on is applicable: every few hours every few mins every few secs item1 item2 item3 .. .. .. item10 so the sample data looks like this: id item1 item 2 ............. item10 1 hours hrs ................. mins 2 secs hrs ................. mins 3 mins hrs ................. mins I want to add up the hours secs mins for each item..for example (from the above sample): ev...

A Crystal Beginner
I am using Crystal 9.2.4.77 and have loaded the Crystal enhancements. Now I want to do against the CRM database. What do I do? I thought I would create a data source to the CRM SQLserver, which I did, then connect to it through Crystal Reports. That works, but when I drill down on the AAA_MSCRM database to choose my tables, it shows me dbo as the only option (where did this come from??) and under that are just a few generic tables. No CRM tables. Something's not quite right. What am I missing? file - log on to aps server "KBLawson" <klawson@aetinc.com> wrote in ...

Managing foreign stocks
I have followed the help section on "Convert foreign currencies for investments (my default currency is Canadian, I have bought US stocks), but the conversion amount is entered into the Commissions field. The reporting would be incorrect. What should I do? "Lulu" <anonymous@discussions.microsoft.com> wrote in message news:7bc401c43140$f5b0d010$a301280a@phx.gbl... > I have followed the help section on "Convert foreign > currencies for investments (my default currency is > Canadian, I have bought US stocks), but the conversion > amount is entered int...

How to get the CScrollBar's Handle in CTreeCtrl?
Hey,All: I thought I have a problem when I trid to get the CScrollBar's handle from my CTreeCtrl extended handle. Can anybody tell me whether I can get the handle of the CScrollBar from the CTreeCtrl? Thanks in advance! Carl :-| Carl wrote: > Hey,All: > > I thought I have a problem when I trid to get the CScrollBar's handle from > my CTreeCtrl extended handle. > Can anybody tell me whether I can get the handle of the CScrollBar from the > CTreeCtrl? > > Thanks in advance! > Carl > :-| > > Sorry, it is not that simple. The scroll bars that...

Cannot get fast forward or fast reverse to work with WMP 11
I am running Vista Home Premium on a HP G 217-EM Notebook which comes pre-installed with Windows Media Player 11. When I play cds and try to fast forward or fast reverse by keeping the fast forward or fast reverse buttons constantly depressed nothing happens. Why is this, and can anyone come up with a solution? Many thanks This doesn't work on my system either, so it's probably just a limitation of WMP. Fast forward and fast reverse should work fine when you rip the CD's to MP3 or WMA files, and play these files instead. Regards -- Tim De Baets http://www....

Table formatting lost
I receive emails that started off in Excel as a short table. The sender then cuts and pastes into Outlook. When the message arrives it has lost all formatting for the table. Is there any solution apart from sennding as an Excel attachment? Do the copy as a Picture and then paste in Outlook. -- Gary''s Student - gsnu2007k "him@privacy.net" wrote: > I receive emails that started off in Excel as a short table. The > sender then cuts and pastes into Outlook. When the message arrives it > has lost all formatting for the table. Is there any solution apart > from se...

vlookup and Access Database Table
Can vlookup be used to get a result from an Access Database Table? Thanks. The vlookup function itself is an Excel function and as such can only retrieve data from an excel sheet. However you may be able to use the import external data menu option in the Data menu to retrieve your data from the access database, pull it into your excel workbook and then use the vlookup function. I never tried this myself, but maybe the idea can be applied. -- Jeroen van Nieuwkerk "finster26" wrote: > Can vlookup be used to get a result from an Access Database Table? > > Thanks....

Get paid while you get online!!
I found a great Internet company - Cashfiesta.com - that has created a product everyone can benefit from. They pay you while you work or play on your computer. All you need to do is keep their software - the FiestaBar=99 - active while you are online. They even pay you when your friends are using their computers. Unlike other companies, Cashfiesta gives you control over how much money you earn. They have an individual payrate based on the number of Special Offers you sign up for. As some of these offers are free, you can increase your payrate up to 33 times without spending a penny. It's...

Can't get auto-update (update) to install
Version: 2008 Operating System: Mac OS X 10.4 (Tiger) Processor: Power PC I've been trying to manually check for updates to Word 2008, and I get a &quot;critical update&quot; notice, asking me to install auto-update. When I try to install it, I cannot. It just keeps repeating the attempt, in an &quot;endless loop.&quot; What to do? <br> Thank you. ...

Spreadsheet getting corrupted
Hello All: I have a relatively large spreadsheet. I am getting errors (see after my signature line). What could be causing these errors? Is it that the spreadsheet is too large? Thanks Deguza -------------------------------------------------------- Microsoft Office Excel File Repair Log Errors were detected in file 'C:\Documents and Settings\deguza\My Documents\sales\Sales_2006_2007.xls' The following is a list of repairs: Global PivotTable report information was repaired due to integrity problems. Global PivotTable report information was repaired due to integrity problems. Glo...

Reg getting the next IV Document Number field !
Hi, I am creating a window in dexterity similar to the item transaction entry window (Transactions>Inventory> Transaction Entry). In the Item transaction Entry window, the Document number field defaults to the next document number when we move the focus to that field. I wanted to know if there is any function , or table that i can access to get the next document number in the new window that i am creating. Thanks, swetha -- swetha >In the Item transaction Entry window, the Document number field defaults to the next document number when we move the focus to that field.< T...

referencing a cell determined by name in another cell
How do I reference a cell within a formula based on the contents of another cell? For example if one cell contained a reference/address for a column array, how could I refer to this cell (and hence the column array) within the vlookup function instead of having to put in the actual table array. In other words an external way of changing the table array rather than going into the formula. VLOOKUP(lookup_value,table_array,col_index_num,range_lookup) Hi use INDIRECT for this -- Regards Frank Kabel Frankfurt, Germany "ricardo wants answers" <ricardo wants answers@discussion...

How do I get??
Sorry if this seems a fairly easy question to you guys. I have a spreadsheet and I need to get the current system time into a cell. The format of the time is hh:mm am/pm. Any assistance would be most helpful. Hi try =INT(NOW()) in this cell and format is to your needs -- Regards Frank Kabel Frankfurt, Germany PM wrote: > Sorry if this seems a fairly easy question to you guys. > > I have a spreadsheet and I need to get the current system time into a > cell. The format of the time is hh:mm am/pm. > > Any assistance would be most helpful. PM, in the cell you want pu...

Table of contents
I have created a large spreadsheet with numerous worksheets and would like to be able to insert a table of contents at the front of the report. Each heading in the table of contents would be the worksheet name. Is there any way of doing this? I know I can put a table of contents page in the report and fill in the page numbers by manually doing a print preview and then filling in each page number manually. Any help would be greatly appreciated. Hi have a look at http://www.mvps.org/dmcritchie/excel/buildtoc.htm -- Regards Frank Kabel Frankfurt, Germany Dave wrote: > I have created a l...

Get notified when Out of Office is on
I am using Outlook 2007. With 2003, when returning from leave, I used to get a notification that the Outlook out of office was still on and asking me if I wanted to switch it off. This reminder no longer appears with 2007. How can I switch this setting on so that I get the notification? "Mary Ann" <MaryAnn@discussions.microsoft.com> wrote in message news:ED5533A7-D0EA-41B8-B1A0-A9D15FB6FD98@microsoft.com... >I am using Outlook 2007. With 2003, when returning from leave, I used to get > a notification that the Outlook out of office was still on and asking me ...

over VPN, it gets stuck when sending outgoing email
When I use VPN to connect to work from home, the outlook can not finish sending outgoing emails. The progress bar moves to the end but then stops there forever. It can never finish. The receiving of new incoming emails work fine. All other network functionality works, e.g. internet browsing, telnet, ftp, etc, all work fine. My system is win2k. I use linksys wireless DSL router. I'd appreciate any hint! Are you using Exchange server? I'd set up your mail profile to prompt you to work offline or online - when using VPN, work offline with scheduled syncs. If not using exchange, pos...

Regarding RMS software Key
Hello, I recently had to reinstall my pos system as well as my headquarters client. after the install i was looking through my keys (i have about 16) and noticed that the key for my headquarters client was gone. Does anyone happen to know how i can get my software working? Oh!!! You can active the Key once, you can send to mail to the partner or write the case to Microsoft!... Roberto Monge "Steve" wrote: > Hello, > > I recently had to reinstall my pos system as well as my headquarters client. > after the install i was looking through my keys (i have about 16...

TAB Key doesn't work in my DLL dialog app
I created a dialog based application in a DLL. When I run my dialog, I can not Tab between items. Basically the Tab key doesn't do anything. Is there a fix to this.... am I missing some option somewhere in MFC? Is it by any chance a MFC Regular DLL and you are dealing with a modeless dialog? --- Ajay Marek wrote: > I created a dialog based application in a DLL. > > When I run my dialog, I can not Tab between items. Basically the Tab > key doesn't do anything. > > Is there a fix to this.... am I missing some option somewhere in MFC? yes Ajay Kalra wrote: >...

Can I share a table template I created in Quick Tables?
I have created a few table templates and saved them into the Quick Tables in Word. I would like to make these available for other users of my document. What can I do to make these ready available in their Quick Tables short of saving them individually to each work station? Can they import or save them when they open your document? "brigla5" wrote: > I have created a few table templates and saved them into the Quick Tables in > Word. I would like to make these available for other users of my document. > What can I do to make these ready available in th...

Getting Control ID in Active X control
GetWindowLong return 0. You need to call GetDlgCtrlID from outside the activex control as the function available within the control returns an arbitrary value of zero. Take a look at this article http://xendra.ens.uabc.mx/~sinfante/loo/libro/ch17_4.htm particularly the paragraph preceeding the title "MFC and Ambient Properties". This really begs the question why you want the ID in the first place as activex controls have to be fully self containing to operate - with a few exceptions where sibling controls need to be able to locate each other. - Tim "ytv" <...