Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 General SQL Server Forums
 New to SQL Server Programming
 EXEC Syntax Error

Author  Topic 

yellowman
Starting Member

25 Posts

Posted - 2012-11-28 : 16:11:38
Anyone know where I am going wrong here:


EXEC('IF EXEC sp_executesql N''' +@command+ ' = '' '' '' PRINT ''' +@DB_Name+ '''')


The error says the following
Incorrect syntax near the keyword 'EXEC'.
Msg 170, Level 15, State 1, Line 2
Line 2: Incorrect syntax near ' '.

Thanks

Elizabeth B. Darcy
Starting Member

39 Posts

Posted - 2012-11-28 : 17:49:56
Looks like you have couple of extra spaces. Try if this works?
EXEC('IF EXEC sp_executesql N''' +@command+ ' =  '''''' PRINT ''' +@DB_Name+ '''')


________________________________________
-- Yes, I am indeed a fictional character.
Go to Top of Page

madhivanan
Premature Yak Congratulator

22864 Posts

Posted - 2012-11-29 : 02:47:54
What are you trying to do with that code? You can't use IF on EXEC

Madhivanan

Failing to plan is Planning to fail
Go to Top of Page

yellowman
Starting Member

25 Posts

Posted - 2012-11-29 : 08:52:35
Your right, using IF in that statement above doesn't work. I know what I want, I just don't know how to get there.

@command is a SELECT statement that either outputs a number or returns and empty set. If @command returns an empty set, I want to output the database name (@DB_Name).

I tried to eliminate the IF statement (below), but that didn't work either.


SELECT @command = 'USE ' +@DB_Name+ '
SELECT * FROM '
+@DB_Name + '.CQ_DBO.schema_version'


EXEC('sp_executesql N''''' +@command+ ' ISNULL PRINT ''' +@DB_Name+ '''''''')

Go to Top of Page

nigelrivett
Master Smack Fu Yak Hacker

3385 Posts

Posted - 2012-11-29 : 10:43:49
declare @t table (format for return from select statement)
select @command = 'SELECT * FROM ' + @DB_Name + '.CQ_DBO.schema_version'

insert @t
exec (@command)

if not exists (select * from @t)
PRINT @DB_Name

==========================================
Cursors are useful if you don't know sql.
SSIS can be used in a similar way.
Beer is not cold and it isn't fizzy.
Go to Top of Page
   

- Advertisement -