Nerdynosaur
Nerdynosaur

Reputation: 1888

MySQL if Execution Exists

i try to set an Existence when there is a data found in my table(user). In the query, i need to use a variable. However, in the IF case, it doesn't work. Any ideal? or any alternative way to do it?

DECLARE
@myTableName varchar(1000), 
@myQuery varchar(1000)

SET @myTableName = userTable   //the userTable i will retrieve from a parameter
SET @myQuery = 'SELECT TOP 1 1 FROM  ' + @myTableName + ''


IF EXISTS (EXEC(@myQuery))
    BEGIN
        print('Success')
    END
ELSE
    BEGIN
        print('Failed')
    END

Upvotes: 0

Views: 54

Answers (1)

Fabien TheSolution
Fabien TheSolution

Reputation: 5050

SET @myQuery = 'SELECT * FROM  ' + @myTableName + ' LIMIT 0,1 '

If it doesn't work, you can try this approach :

DECLARE
@myTableName varchar(1000), 
@i int

SET @myTableName = userTable   //the userTable i will retrieve from a parameter
SET @i = 'SELECT count(*) AS cnt FROM  ' + @myTableName + ''

IF @i > 0
    BEGIN
        print('Success')
    END
ELSE
    BEGIN
        print('Failed')
    END

Upvotes: 1

Related Questions