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

前端 未结 3 772
余生分开走
余生分开走 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);'
    

提交回复
热议问题