Finding a Primary Key Constraint on the fly in SQL Server 2005

前端 未结 3 768
余生分开走
余生分开走 2021-01-14 10:22

I have the following SQL:

 ALTER TABLE dbo.PS_userVariables DROP CONSTRAINT PK_PS_userVariables;
 ALTER TABLE dbo.PS_userVariables ADD PRIMARY KEY (varnumber         


        
相关标签:
3条回答
  • 2021-01-14 10:56
    DECLARE @TableName varchar(128)
    DECLARE @IndexName varchar(128)
    DECLARE @Command varchar(1000)
    
    SET @TableName = 'PS_userVariables'
    
    SELECT @IndexName = si.name
    FROM sys.tables st
    JOIN sys.indexes si ON st.object_id = si.object_id
    WHERE st.name = @TableName
      AND si.is_primary_key = 1
    
    SET @Command = 'ALTER TABLE dbo.' + QUOTENAME(@Tablename) + ' DROP CONSTRAINT ' + QUOTENAME(@IndexName) + ';
    ALTER TABLE dbo.' + QUOTENAME(@Tablename) + ' ADD PRIMARY KEY (varnumber, subjectID, userID, datasetID, listid, userVarTitle);'
    
    0 讨论(0)
  • 2021-01-14 11:04
    SELECT 
       A.TABLE_NAME, 
       A.CONSTRAINT_NAME, 
       B.COLUMN_NAME
    FROM 
       INFORMATION_SCHEMA.TABLE_CONSTRAINTS A, 
       INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE B
    WHERE 
          CONSTRAINT_TYPE = 'PRIMARY KEY' 
       AND A.CONSTRAINT_NAME = B.CONSTRAINT_NAME
    ORDER BY 
       A.TABLE_NAME 
    

    Ref: Pinal Dave @ http://blog.sqlauthority.com/2008/09/06/sql-server-find-primary-key-using-sql-server-management-studio/

    0 讨论(0)
  • 2021-01-14 11:20

    While the typical best practice is to always explicitly name your constraints, you can get them dynamically from the catalog views:

    DECLARE @table NVARCHAR(512), @sql NVARCHAR(MAX);
    
    SELECT @table = N'dbo.PS_userVariables';
    
    SELECT @sql = 'ALTER TABLE ' + @table 
        + ' DROP CONSTRAINT ' + name + ';'
        FROM sys.key_constraints
        WHERE [type] = 'PK'
        AND [parent_object_id] = OBJECT_ID(@table);
    
    EXEC sp_executeSQL @sql;
    
    ALTER TABLE dbo.PS_userVariables ADD CONSTRAINT ...
    
    0 讨论(0)
提交回复
热议问题