0

I'm not convinced my title accurately represents my problem, but here is what I have:

DECLARE @ListOfTables TABLE(
    RowID INT NOT NULL PRIMARY KEY IDENTITY(1,1)
    , TableName VARCHAR(200)
)

DECLARE @RowsToProcess INT
DECLARE @CurrentRow INT
DECLARE @TableName VARCHAR(200)


INSERT INTO @ListOfTables (TableName)
VALUES ('Books')
INSERT INTO @ListOfTables (TableName)
VALUES ('Magazines')
INSERT INTO @ListOfTables (TableName)
VALUES ('Essays')

SET @RowsToProcess = @@ROWCOUNT 
SET @CurrentRow = 0

I want to then loop through this table and delete.

WHILE @CurrentRow < @RowsToProcess
BEGIN 
    SET @CurrentRow = @CurrentRow+1

    SELECT @TableName = TableName
    FROM @ListOfTables
    WHERE RowID = @CurrentRow

    DELETE FROM @TableName

END

In actuality, my delete isn't just deleting the table - it has specific criteria. I've simplified it for demonstration purposes.

The error I get here is: Must declare the variable '@TableName'.

I've moved it into the WHILE loop and I receive the same error.

What can I do here? Is it possible to do what I'm trying to do?

0

1 Answer 1

1

Assuming you actually have tables in your db named books, magazines, and essays, and you want to delete from them, or do some query on them, you need to use dynamic sql. Not sure how it's done in MySQL, but in SQL-Server, it'd be like this (highly simplified example):

SET @sql = 'DELETE FROM ' + @TableName;
EXEC (@sql);
Sign up to request clarification or add additional context in comments.

1 Comment

Just be careful where you are getting the data for the @TableName. You could open yourself to a sql injection.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.