473,750 Members | 2,596 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

How to list tables with Primary keys

Hello,

We imported a bunch of tables from a database and realized that the
primary keys weren't copied to the destination db. In order to re-
create the keys, we need to know which tables have them. Is there a
command that I can use (on the source db) to find out which tables
contain primary keys? The db has hundreds of tables and I'd rather not
go through each one to see which has a primary key.

Also, for future reference, is there a way to include the primary key
on an import?

Thanks,
Peps

Jun 9 '07 #1
2 9164
Danny (dl******@gmail .com) writes:
We imported a bunch of tables from a database and realized that the
primary keys weren't copied to the destination db. In order to re-
create the keys, we need to know which tables have them. Is there a
command that I can use (on the source db) to find out which tables
contain primary keys? The db has hundreds of tables and I'd rather not
go through each one to see which has a primary key.
Hopefully all tables have primary keys!

It would have helped if you had said which version of SQL Server you are
using. The query below will run on both SQL 2000 and SQL 2005, but the
old system tables are deprecated on SQL 2005, so had I known you were
using SQL 2005, I would have used the new catalog views instead.

If you did not bring over the primary keys, I suspect that no indexes at
all were copied. This query lists all indexes in a database, and the
column ispk indicates that the index is a primary key. The column
isuniqueconst indicates whether the index is a UNIQUE constraint.

Note that the query as I've written it, will only include the first
five columns in the index. Neither does include information about
ascending/descening, and other less commonly used index properties.

SELECT o.name, i.name,
isclustered = Indexproperty(o .id, i.name, 'IsClustered'),
isunique = Indexproperty(o .id, i.name, 'IsUnique'),
ispk = CASE WHEN o2.xtype = 'PK' THEN 1 ELSE 0 END,
isuniqueconst = CASE WHEN o2.xtype = 'UQ' THEN 1 ELSE 0 END,
cols = ik.col1 + coalesce(', ' + ik.col2, '') +
coalesce(', ' + ik.col3, '') + coalesce(', ' + ik.col4, '') +
coalesce(', ' + ik.col5, '')
FROM sysobjects o
JOIN sysindexes i ON o.id = i.id
LEFT JOIN sysobjects o2 ON o2.name = i.name
AND o2.parent_obj = o.id
JOIN (SELECT ik.id, ik.indid,
col1 = MIN(CASE ik.keyno WHEN 1 THEN c.name END),
col2 = MIN(CASE ik.keyno WHEN 2 THEN c.name END),
col3 = MIN(CASE ik.keyno WHEN 3 THEN c.name END),
col4 = MIN(CASE ik.keyno WHEN 4 THEN c.name END),
col5 = MIN(CASE ik.keyno WHEN 5 THEN c.name END)
FROM sysindexkeys ik
JOIN syscolumns c ON ik.id = c.id
AND ik.colid = c.colid
GROUP BY ik.id, ik.indid) AS ik ON i.id = ik.id
AND i.indid = ik.indid
WHERE Indexproperty(i .id, i.name, 'IsHypothetical ') = 0
AND Indexproperty(i .id, i.name, 'IsStatistics') = 0
AND Indexproperty(i .id, i.name, 'IsAutoStatisti cs') = 0
ORDER BY o.name, i.indid
Also, for future reference, is there a way to include the primary key
on an import?
There is. But I don't know which tool you used, which version of SQL Server
you have etc. Personally, I prefer to build databases from scripts. When
I need to copy a database, I prefer to use BACKUP/RESTORE.

--
Erland Sommarskog, SQL Server MVP, es****@sommarsk og.se

Books Online for SQL Server 2005 at
http://www.microsoft.com/technet/pro...ads/books.mspx
Books Online for SQL Server 2000 at
http://www.microsoft.com/sql/prodinf...ons/books.mspx
Jun 9 '07 #2
On Jun 8, 7:59 pm, Danny <dlapi...@gmail .comwrote:
Hello,

We imported a bunch of tables from a database and realized that the
primary keys weren't copied to the destination db. In order to re-
create the keys, we need to know which tables have them. Is there a
command that I can use (on the source db) to find out which tables
contain primary keys? The db has hundreds of tables and I'd rather not
go through each one to see which has a primary key.

Also, for future reference, is there a way to include the primary key
on an import?

Thanks,
Peps
What are all the keys used in a database

http://www.sqlhacks.com/faqs/list_all_keys

USE AdventureWorksL T;
go

SELECT schm.name AS 'Schema', tbl.name AS 'Table'
, KEYS.name AS 'Constraint', KEYS.type_desc AS 'Type'
, cols.name AS 'Column'
FROM sys.key_constra ints AS KEYS
JOIN sys.TABLES AS tbl
ON tbl.object_id = KEYS.parent_obj ect_id
JOIN sys.schemas AS schm
ON schm.schema_id = tbl.schema_id
JOIN sys.index_colum ns AS idxcols
ON idxcols.object_ id = tbl.object_id
AND idxcols.index_i d = KEYS.unique_ind ex_id
JOIN sys.COLUMNS AS cols
ON cols.object_id = tbl.object_id
AND cols.column_id = idxcols.column_ id
ORDER BY 1,2,3,4;
go
AND

What are all the tables without a primary key?

http://www.sqlhacks.com/faqs/no_primary_key

USE sql911;
go

SELECT SCHEMA_NAME(sch ema_id) AS "Schema", name AS "Table"
FROM sys.TABLES
WHERE OBJECTPROPERTY( object_id,'Tabl eHasPrimaryKey' ) = 0
ORDER BY 1,2;
go

This includes samples and explanations on how to do it.

Also new this week:

SQL Server index performance
SQL Server - optimization:in dex performance
How to group items into a fixed number of bucket with MS SQL Server
How to have a simple server monitoring in MS SQL Server
What's the current version of MS SQL Server used?
What are all the triggers used in a database
What are all the views in a database in MS SQL Server?
What are all the stored procedures in a database in MS SQL Server?
What's the structure of a table with MS SQL Server?

Jun 12 '07 #3

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

0
1409
by: Miguelito Bain | last post by:
hi everybody- i've got a conundrum... i inherited some old databases, and i'm trying to convert them. i run office xp with access 2002, and all of the databases i manage are either in 97 format or 2000 format. i have a list box that works in access 97 but not 2000. here's my situation...
0
1916
by: Susan Bricker | last post by:
The following error: "The current field must match the join key '?' in the table that seves as t the 'one' side of one-to-many relationship. Enter a record in the 'one' side table with the desired key value, and then make the entry with the desired join key in the 'many-only' table." ... happens when I click on an entry of a combobox. HELP!! Here's the background:
1
1174
by: pau | last post by:
Hello, i need your help again. Now im building a table with all the hotels in my town. I put two columns. One with the name and one with a code in autonumber. I create a relation with other table and i want to know if is posible only writing the code the access writes the name and more information in this other table. Thank you.
2
2061
by: DickChristoph | last post by:
Hi I tried posting this query in microsoft.public.sqlserver.programming but got no response. I am new to replication but I am trying to setup up a transactional replication of tables from one database to another in MSSQL 2000 (SP2). My target tables have primary keys defined. Under publication properties I go to the snapshot tab and for each table I clear the check box that says
2
1669
by: smadden | last post by:
I have a simple Access database with 4 tables so far. Here is my question: Talble 2 lists "vulns" and there descriptions. Each has its own primary key and relates to table 1. Table 3 lists "controls" and there descriptions. Each has its own primary key. Many of each can relate to many in table 2. Table 4 is a Merge Table, listing each primary key from table 2 and its relation (primary key) from table 3.
2
1663
by: stevenkwlee | last post by:
Hi I'm new to Access (2003) and i've just been given the horrible horrible task of trying to add extra functionality to an exisiting access database. I'm usually alright in the database front, since i've worked with mysql etc. But this relationship thing is really bugging the heck out of me. First of all there's a few tables which contains primary keys from different tables (they are highlighted in bold) and then a relationship link to it...
2
8263
by: Bobby | last post by:
Hi, Not sure if this is Access, SQL or ODBC. I have a SQL database with an Access Front End. They are linked with ODBC. Occasionally (it's happened 3 times in 4 months) some of the linked tables in Access become read only and I can't add new records to them. If I go into design view (in Access) the tables have lost their Primary Key. In SQL, they still work just fine. The only way I have found to get the links working again is to delete...
11
3675
by: shriil | last post by:
Hi I have this database that calculates and stores the incentive amount earned by employees of a particular department. Each record is entered by entering the Date, Shift (morn, eve, or night) and the 'employee name'. There is another table which assigns an ID to the Shifts, i.e. 1,2 and 3 for morn, eve & night shifts respectively. From the mother table, the incentive is calculated datewise for each employee as per his shift duty. In...
6
4061
by: NicoleCartrette | last post by:
Going back to school is easier said than done.. This was posted to an older thread earlier but I don't think it got any attention. Your help is appreciated Professor requires we create a simple database and specified what are to be the primary keys and relationships etc. I have created the four tables and established the neccessary one to many and many to one relationships between primary keys in the tables with the exception of one...
0
9001
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9583
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
9256
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8263
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6808
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6081
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4716
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
3323
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
2807
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.