Incorrect syntax near 'sp_executesql'
Asked Answered
B

3

8

I don't understand why the following is giving me the error. I thought it was related to the commented out section, 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
Brigette answered 18/8, 2009 at 22:54 Comment(0)
C
16

This is 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 can't just call a stored proc without an exec when you are in a block.

Converter answered 18/8, 2009 at 22:57 Comment(2)
You can call a stored proc without and exec, but only when the call to the stored proc is the only statement in the block.Coenocyte
it has to be the First statement, not necessarily the only one.Pennate
Q
3

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

Optionally you can put an exec before sp_executesql.

Quartile answered 18/8, 2009 at 22:56 Comment(0)
W
0

On some occasions I had to use master as well:

exec master..sp_executesql 
Wrens answered 3/11, 2009 at 3:13 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.