Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Incorrect syntax near 'sp_executesql'

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
like image 490
OMG Ponies Avatar asked Aug 18 '09 22:08

OMG Ponies


2 Answers

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.

like image 111
Sam Saffron Avatar answered Sep 20 '22 01:09

Sam Saffron


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.

like image 33
ahsteele Avatar answered Sep 20 '22 01:09

ahsteele