Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Use CONVERT in dynamic SQL 1

Status
Not open for further replies.

robertfah

Programmer
Mar 20, 2006
380
US
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:
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?
 
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)

Do not extract CONVERT() from the whole string.



Borislav Borissov
VFP9 SP2, SQL Server 2000,2005 & 2008.
 
Do not extract CONVERT() from the whole string.
Ah, I knew I was missing something simple. And just for anyone else who may read this, I had to change the variable to nvarchar(MAX) and use EXEC sp_executesql to get it to run, otherwise it throws the following error:
Code:
Server: Msg 203, Level 16, State 2, Line 10
The name '
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' is not a valid identifier.

So the new SQL looks like this:
Code:
DECLARE @SQL nvarchar(MAX)

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 sp_executesql @SQL

Thanks again bborissov for the help!
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top