Dropping foreign key using variable as name

后端 未结 3 1365
迷失自我
迷失自我 2021-01-23 03:36

I use the following:

DECLARE @ConstraintName varchar(255);
SELECT @ConstraintName = CONSTRAINT_NAME 
FROM 
   INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE 
WHERE 
         


        
相关标签:
3条回答
  • 2021-01-23 04:02
    DECLARE @constraintName VARCHAR(50);
    DECLARE @runString VARCHAR(2000);
    
    select @constraintName = CONSTRAINT_NAME
    from INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE
    WHERE TABLE_NAME = 'TheTable' AND COLUMN_NAME = 'TheColumn';
    
    
    SET @runString = CONCAT('ALTER TABLE TheTable DROP CONSTRAINT ', @constraintName);
    PREPARE stmt1 FROM @runString ;
    EXECUTE stm1;
    DEALLOCATE PREPARE stmt1;
    
    0 讨论(0)
  • 2021-01-23 04:03

    Try this

    SELECT CONSTRAINT_NAME INTO @ConstraintName 
    FROM 
       INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE 
    WHERE 
       TABLE_NAME = 'TheTable' 
       AND COLUMN_NAME = 'TheColumn';
    
    SET @queryStr = CONCAT('alter table TheTable drop constraint ', @ConstraintName);
    PREPARE qry from @queryStr;
    EXECUTE qry;
    

    For more information: https://dev.mysql.com/doc/refman/5.7/en/execute.html

    0 讨论(0)
  • 2021-01-23 04:05

    Try this :

    DECLARE @ConstraintName VARCHAR(255);
    SELECT CONSTRAINT_NAME 
    INTO @ConstraintName 
    FROM 
       INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE 
    WHERE 
       TABLE_NAME = 'TheTable' 
       AND COLUMN_NAME = 'TheColumn';
    
    alter table TheTable drop constraint @ConstraintName;
    

    Or :

    DECLARE @ConstraintName VARCHAR(255);
    SELECT @ConstraintName:=CONSTRAINT_NAME 
    FROM 
       INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE 
    WHERE 
       TABLE_NAME = 'TheTable' 
       AND COLUMN_NAME = 'TheColumn';
    
    alter table TheTable drop constraint @ConstraintName;
    
    0 讨论(0)
提交回复
热议问题