Wrox Programmer Forums
Go Back   Wrox Programmer Forums > SQL Server > SQL Server 2000 > SQL Server 2000
SQL Server 2000 General discussion of Microsoft SQL Server -- for topics that don't fit in one of the more specific SQL Server forums. version 2000 only. There's a new forum for SQL Server 2005.
Welcome to the p2p.wrox.com Forums.

You are currently viewing the SQL Server 2000 section of the Wrox Programmer to Programmer discussions. This is a community of software programmers and website developers including Wrox book authors and readers. New member registration was closed in 2019. New posts were shut off and the site was archived into this static format as of October 1, 2020. If you require technical support for a Wrox book please contact http://hub.wiley.com
Old November 28th, 2006, 10:26 PM
Authorized User
Join Date: Mar 2006
Posts: 14
Thanks: 0
Thanked 0 Times in 0 Posts
Default Retrieving Primary Key columns from system tables

     I'm trying to retrieve table name, field name, datatype, length, null/not null, primary key from system tables. I'm able to pull successfull all of them except primary key columns. Can anyone please help me. Here is my sql query.

select a.name as TableName,b.name as FieldName,c.name as Datatype,b.length as Length,
    AllowNulls = (CASE
      WHEN b.isnullable=0 THEN 'NOT NULL'
      WHEN b.isnullable=1 THEN 'NULL'
from sysobjects a,syscolumns b,systypes c
where a.type='U'
and a.id = b.id and c.xtype=b.xtype
order by a.name,b.colorder

I want to add the primary key column, saying if the field is a primary key it should display as yes otherwise no.

I hope someone can help me. I have been trying this from a long time. I need this immediately.

Thanks for your help in advance.

Old November 28th, 2006, 11:23 PM
Friend of Wrox
Join Date: Oct 2006
Posts: 475
Thanks: 0
Thanked 9 Times in 9 Posts

I believe if you "AND" the "ColStat" column from SysColumns with 1 and get a 1, the column is a primary key column. If you want to know the order of the columns for a composite primary key, take a look and the system stored procedure called sp_pkeys and disect it.

--Jeff Moden

Similar Threads
Thread Thread Starter Forum Replies Last Post
Foreign key not updating with Primary key xavier1945 BOOK: Access 2003 VBA Programmer's Reference 2 July 4th, 2007 09:48 PM
Retrieving Primary key in DataGrid shahchi1 ASP.NET 1.0 and 1.1 Basics 10 August 10th, 2004 03:21 PM
FOREIGN KEY and PRIMARY KEY Constraints junemo Oracle 10 June 15th, 2004 01:00 AM
Get primary Key Columns From Access Table MeSaqi Access VBA 0 July 18th, 2003 08:20 AM

Powered by vBulletin®
Copyright ©2000 - 2020, Jelsoft Enterprises Ltd.
Copyright (c) 2020 John Wiley & Sons, Inc.