SQL Server Primary Key Discovery Script Using sp_pkeys and sysobjects

SQL Server Primary Key Discovery Script Using sp_pkeys and sysobjects

Purpose

This SQL Server script generates dynamic SQL statements that can be executed to discover primary keys across all user tables in a database. It's a powerful administrative tool that helps database administrators quickly identify primary key constraints without manually checking each table individually.

Code Breakdown

1select 'select "Processing Table ' + name + '"go' + ' sp_pkeys ' + name + 'go' 
2from sysobjects 
3where type = 'U' 
4order by name

Let's break down each component of this query:

SELECT Statement Components

  1. Dynamic String Construction: The SELECT clause builds a string that combines:
    • A status message indicating which table is being processed
    • The sp_pkeys system stored procedure call
    • The table name as a parameter
  2. sysobjects System Table: The FROM clause queries the sysobjects system catalog view, which contains metadata about database objects
  3. Filtering Criteria: The WHERE clause type = 'U' filters for user tables only, excluding system tables and other object types
  4. Ordering: Results are ordered alphabetically by table name for consistent output

Key Points and Insights

What the Script Accomplishes

  • Automated Discovery: Eliminates manual effort in checking primary keys across multiple tables
  • Batch Processing: Creates executable SQL statements for all user tables at once
  • Systematic Approach: Processes tables in alphabetical order for organized results

Understanding sp_pkeys

The sp_pkeys stored procedure is a SQL Server system procedure that:

  • Returns primary key information for specified tables
  • Provides column names, key sequences, and constraint details
  • Works with both local and linked server tables

System Table Insights

The sysobjects table contains crucial metadata:

  • type = 'U': User tables (excludes system tables, views, procedures)
  • name column: Contains the actual table names
  • Compatibility: Works across different SQL Server versions

Practical Applications

Database Documentation

Use this script to generate documentation about primary key structures across your database schema.

Migration Planning

Essential for understanding table relationships before database migrations or upgrades.

Performance Analysis

Identify tables without primary keys that might benefit from adding clustered indexes.

Code Generation

Generate repetitive administrative scripts for large databases with many tables.

Example Output

When executed, this script produces output similar to:

1select "Processing Table Customers"go sp_pkeys Customersgo
2select "Processing Table Orders"go sp_pkeys Ordersgo
3select "Processing Table Products"go sp_pkeys Productsgo

Best Practices

  1. Test Environment First: Always run generated scripts in a test environment before production
  2. Review Output: Examine the generated SQL before execution
  3. Documentation: Save results for database documentation purposes
  4. Regular Audits: Use periodically to ensure primary key consistency

Modern Alternatives

While this script uses sysobjects (compatibility view), consider modern alternatives:

  • sys.tables and sys.key_constraints for newer SQL Server versions
  • INFORMATION_SCHEMA.TABLE_CONSTRAINTS for ANSI SQL compliance

Troubleshooting Tips

  • Ensure sufficient permissions to query system tables
  • Verify database context before execution
  • Check for special characters in table names that might cause issues

References

Posts in this series