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

前端 未结 3 771
余生分开走
余生分开走 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 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 ...
    

提交回复
热议问题