I've got some SQL that I can get to run just fine but as soon as I convert it to dynamic SQL, it errors out. I know why it errors out, I just don't know how to get around it.
Here's my SQL when it works:
Now if I make it dynamic, it fails:
It give me:
Which I understand, it can't find that column because it hasn't compiled the dynamic part yet....but how can I get around this? I am basically trying to concatinate text with an ID field.
Any ideas?
Here's my SQL when it works:
Code:
SELECT LocationID, 11, 70, 'TSS-1', NULL, 'TBD-' + CONVERT(varchar, LocationID)
FROM Locations
WHERE LocationID NOT IN (Select r.LocationID
FROM Rooms r)
AND CustomerID = 40
Now if I make it dynamic, it fails:
Code:
DECLARE @SQL varchar(8000)
SET @SQL = '
SELECT LocationID, 11, 70, ''TSS-1'', NULL, ''TBD-' + CONVERT(varchar, LocationID) + '''
FROM Locations
WHERE LocationID NOT IN (Select r.LocationID
FROM Rooms r)
AND CustomerID = 40'
EXEC(@SQL)
It give me:
Code:
Server: Msg 207, Level 16, State 1, Line 4
Invalid column name 'LocationID'.
Which I understand, it can't find that column because it hasn't compiled the dynamic part yet....but how can I get around this? I am basically trying to concatinate text with an ID field.
Any ideas?