Today I started to create a rather simple stored procedure that I thought would take a few minutes... Well it fell into the "20 minute" rule... if you estimate about "20 minutes" it won't be...
Anyway, this procedure needed to build SQL Select based on parameters passed in. So, I needed to user SQL EXECUTE statement. I create @SQL as the varchar that I contained the select statement and passed the command to the EXECUTE.. When procedure ran, I got the MSG 203 error message, but it was truncated due to the length of the SQL statement.. No problem, off to Books Online to determine what the MSG 203 message -- not there... Google?
OK .. 20 minutes later I finally discovered that any statement I passed into the EXECUTE statement did not work. Hmmmm. So back to the EXECUTE statement documentation. Seems that I had missed a little detail. If you are using a variable -- eg. @SQL in my case -- you must surround the EXECUTE parameter statement in brackets.
So...(using the NorthWind database for example)
DECLARE @SQL AS VARCHAR(50)
SET @SQL = 'select * from orders'
EXEC @SQL
doesn't work, but
DECLARE @SQL AS VARCHAR(50)
SET @SQL = 'select * from orders'
EXEC (@SQL) <-- notice the brackets
does... lesson learned. 50 minutes later... The "20 minute" rules lives!