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

Our new SQL Server Forums are live! Come on over! We've restricted the ability to create new threads on these forums.

SQL Server Forums
Profile | Active Topics | Members | Search | Forum FAQ
Save Password
Forgot your Password?

 All Forums
 General SQL Server Forums
 New to SQL Server Programming
 EXEC Syntax Error
 Reply to Topic
 Printer Friendly
Author Previous Topic Topic Next Topic  

Starting Member

25 Posts

Posted - 11/28/2012 :  16:11:38  Show Profile  Reply with Quote
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 ' '.


Elizabeth B. Darcy
Starting Member

United Kingdom
39 Posts

Posted - 11/28/2012 :  17:49:56  Show Profile  Reply with Quote
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

Premature Yak Congratulator

22864 Posts

Posted - 11/29/2012 :  02:47:54  Show Profile  Send madhivanan a Yahoo! Message  Reply with Quote
What are you trying to do with that code? You can't use IF on EXEC


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

Starting Member

25 Posts

Posted - 11/29/2012 :  08:52:35  Show Profile  Reply with Quote
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

Flowing Fount of Yak Knowledge

United Kingdom
3385 Posts

Posted - 11/29/2012 :  10:43:49  Show Profile  Visit nigelrivett's Homepage  Reply with Quote
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)

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
  Previous Topic Topic Next Topic  
 Reply to Topic
 Printer Friendly
Jump To:
SQL Server Forums © 2000-2009 SQLTeam Publishing, LLC Go To Top Of Page
This page was generated in 0.04 seconds. Powered By: Snitz Forums 2000