Incorrect syntax near 'sp_executesql'

I do not understand why the following gives me an error. I thought this was due to the comment, but @SQL is nvarchar (4000).

BEGIN sp_executesql N'SELECT ''td''' --sp_executesql @SQL, N'@StartDate DateTime, @EndDate DateTime, @End2 DateTime, @Program varchar(4)', @StartDate, @EndDate, @End2, @Program END 
+7
sql tsql sql-server-2005 dynamic-sql
source share
3 answers

That's why:

 - This works just fine:
 BEGIN
   - You must have an exec before your sp_executesql or it will not work in a block
   exec sp_executesql N'SELECT '' td '' '
 End

You cannot just call a stored procedure without exec when you are in a block.

+13
source share

Why do you have this in BEGIN ... END? Running an external sp_executesql block will work.

Optionally, you can put exec in front of sp_executesql.

+2
source share

In some cases, I had to use a wizard:

 exec master..sp_executesql 
0
source share

All Articles