2011-12-20 3 views
0

J'essaie d'écrire une petite procédure stockée pour nettoyer la base de données par programme.Erreur de syntaxe dans la procédure stockée

Pour cela,

Première, je laisser tomber toutes les contraintes clés étrangères

deuxième, je laisser tomber toutes les contraintes de clé primaire,

Troisième, je laisse tomber toutes les tables.

J'ai écrit le code suivant à faire plus de trois étapes (troisième étape n'a pas encore démarré)

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 

Je reçois l'erreur suivante:

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'. 

Quelqu'un peut-il s'il vous plaît dire comment résoudre le problème?

Répondre

1

Pourriez-vous s'il vous plaît utiliser ci-dessous, aussi déclarer votre variable en haut de sorte que chaque variable est disponible partout.

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

Vous ne pouvez pas utiliser de variables pour les noms d'objet dans les commandes DDL telles que ALTER TABLE.