2014-05-20 70 views
1

我使用以下命令:刪除外鍵使用變量名

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

+0

Isn「t it SELECT INTO @ConstraintName ... ??? –

+0

@AnthonyRaymond給了我'關鍵字'INTO'附近的語法不正確。 – Joetjah

回答

2
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 = 'ALTER TABLE TheTable DROP CONSTRAINT ' + @constraintName; 
EXECUTE (@runString); 
+0

'添加約束',但'放棄外鍵' –

+0

'concat',而不是'+' –

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; 
+0

他們沒有工作。第一個在@ConstraintName附近有不正確的語法,第二個在':'附近有不正確的語法。 – Joetjah

+0

@Joetjah你可以創建一個SQLFiddle,這樣我們可以自己做一些測試嗎? http://sqlfiddle.com/ –

+0

@Joetjah plus,你在哪裏測試你的請求?命令行,PhpMyAdmin,工作臺,...? –

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