使用变量作为名称删除外键

时间:2014-05-20 10:20:24

标签: mysql sql

我使用以下内容:

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;

但是,它在@ConstraintName附近的语法不正确。这可能是一件小事,但我无法弄清楚。我应该更改什么,以便限制将被删除?

SQLFiddle:http://sqlfiddle.com/#!2/6709e/3

3 个答案:

答案 0 :(得分:3)

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;

答案 1 :(得分:0)

试试这个:

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;

或者:

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;

答案 2 :(得分:0)

试试这个

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;

有关详细信息:https://dev.mysql.com/doc/refman/5.7/en/execute.html