Link to home
Start Free TrialLog in
Avatar of bibi92
bibi92Flag for France

asked on

use variable @dbname in a stored procedure

Hello,

I try to use variable @dbname in a script, the following error is returned :Incorrect syntax near ')'.

declare @dbname as varchar (50)
set @dbname = 'TESTDB'

IF NOT EXISTS (SELECT name FROM ['+@dbname+'].sys.indexes WHERE name = 'TECH_IX_DOMAINID_GROUPID_RECORDTYPE')

Thanks

Regards
Avatar of Vitor Montalvão
Vitor Montalvão
Flag of Switzerland image

You need to put the full select command into a variable and the execute it:
declare @MySelect as varchar (MAX)
declare @dbname as varchar (50)
 set @dbname = 'TESTDB'

set @MySelect = 'IF NOT EXISTS (SELECT name FROM ['+@dbname+'].sys.indexes WHERE name = '''TECH_IX_DOMAINID_GROUPID_RECORDTYPE''')'

EXECUTE(@MySelect)

Open in new window

Avatar of bibi92

ASKER

Thanks Incorrect syntax near 'TECH_IX_DOMAINID_GROUPID_RECORDTYPE'.
ASKER CERTIFIED SOLUTION
Avatar of Deepak Chauhan
Deepak Chauhan
Flag of India image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
So, all the points going to another Expert just because an extra quote?