存储过程中的语法错误

时间:2011-12-20 09:20:28

标签: sql sql-server

我正在尝试编写一个小的存储过程来以编程方式清理数据库。

为此,

首先 ,我正在删除所有外键约束

第二次 ,我将丢弃所有主键约束,

第三次 ,我正在删除所有表格。

我已经编写了以下代码来完成上述三个步骤(第三步尚未开始)

CREATE PROCEDURE usp_CleanupDB AS
BEGIN
--Begin: Code to drop FOREIGN KEY CONSTRAINTS in the database
DECLARE @ForeignKeyConstraint AS VARCHAR(100)
DECLARE @ForeignKeyContainedTableName AS VARCHAR(100)
DECLARE @ForeignKeyConstraintsTableCursor AS CURSOR
SET @ForeignKeyConstraintsTableCursor = CURSOR FOR
SELECT ForeignKeyName, TableName FROM dbo.GetDBForeignKeyConstraints()
OPEN @ForeignKeyConstraintsTableCursor
FETCH NEXT FROM @ForeignKeyConstraintsTableCursor INTO @ForeignKeyConstraint, @ForeignKeyContainedTableName
WHILE @@FETCH_STATUS = 0
BEGIN
    --Drop FOREIGN KEY Constraint
    ALTER TABLE @ForeignKeyContainedTableName DROP CONSTRAINT @ForeignKeyConstraint
    FETCH NEXT FROM @ForeignKeyConstraintsTableCursor into @ForeignKeyConstraint, @ForeignKeyContainedTableName
END
CLOSE @ForeignKeyConstraintsTableCursor
DEALLOCATE @ForeignKeyConstraintsTableCursor
--End: Code to drop FOREIGN KEY CONSTRAINTS in the database
--Begin: Code to drop PRIMARY KEY CONSTRAINTS in the database
DECLARE @PrimaryKeyConstraint AS VARCHAR(100)
DECLARE @PrimaryKeyContainedTableName AS VARCHAR(100)
DECLARE @PrimaryKeyConstraintsTableCursor AS CURSOR
SET @PrimaryKeyConstraintsTableCursor = CURSOR FOR
SELECT PrimaryKeyName, TableName FROM dbo.GetDBPrimaryKeyConstraints()
OPEN @PrimaryKeyConstraintsTableCursor
FETCH NEXT FROM @PrimaryKeyConstraintsTableCursor INTO @PrimaryKeyConstraint, @PrimaryKeyContainedTableName
WHILE @@FETCH_STATUS = 0
BEGIN
    --Drop PRIMARY KEY Constraint
    ALTER TABLE @PrimaryKeyContainedTableName DROP CONSTRAINT @PrimaryKeyConstraint
    FETCH NEXT FROM @PrimaryKeyConstraintsTableCursor INTO @PrimaryKeyConstraint, @PrimaryKeyContainedTableName
END
--End: Code to drop PRIMARY KEY CONSTRAINTS in the database
END

我收到以下错误:

Msg 102, Level 15, State 1, Procedure usp_CleanupDB, Line 15
Incorrect syntax near '@ForeignKeyContainedTableName'.
Msg 102, Level 15, State 1, Procedure usp_CleanupDB, Line 33
Incorrect syntax near '@PrimaryKeyContainedTableName'.

有人可以告诉我们如何解决这个问题吗?

2 个答案:

答案 0 :(得分:2)

您不能在ALTER TABLE等DDL命令中使用变量作为对象名称。

答案 1 :(得分:1)

请您使用以下方式,并在顶部声明您的变量,以便每个变量都可用于所有地方。

EXECUTE('ALTER TABLE ' + @PrimaryKeyContainedTableName + ' DROP CONSTRAINT '+ @PrimaryKeyConstraint)