user1058359
user1058359

Reputation: 183

invalid column name when passing variable mssql

I'm running into this odd issue with this snippet of code:

DECLARE @dbname nvarchar(128)
SET @dbname = $(databaseName)

IF (EXISTS (SELECT name 
FROM master.dbo.sysdatabases 
WHERE ('[' + name + ']' = @dbname 
OR name = @dbname)))

-- code mine :)
PRINT 'true'

I'm passing it through the command line as such:

"C:\Program Files\Microsoft SQL Server\100\Tools\Binn\sqlcmd.exe" -U user -P password -i C:\checkDB.sql -v databaseName=newdatabasetest1

I get this error when I try and run the command here:

Msg 207, Level 16, State 1, Server SERVERNAME, Line 2
Invalid column name 'newdatabasetest1'.

If I change the query to replace $(databaseName) with 'newdatabasetest1' it works and returns 'true' as expected...

I'm not sure what I'm doing wrong here or if maybe it's a SQL thing but it seems to only have issue with the command line. I use the same passing variable technique for creating and droping a database which works fine.

Any guidance would be helpful!

Upvotes: 5

Views: 5224

Answers (2)

Moon
Moon

Reputation: 1151

You need to add single quotes to the value assigned to @dbname, like this:

DECLARE @dbname nvarchar(128)
SET @dbname = '$(databaseName)'

IF (EXISTS (SELECT name 
FROM master.dbo.sysdatabases 
WHERE ('[' + name + ']' = @dbname 
OR name = @dbname)))

PRINT 'true'

Upvotes: 6

user1058359
user1058359

Reputation: 183

The Solution to this was to do SET @dbname = '$(databaseName)' instead of SET @dbname = $(databaseName) it works in the actual query program, but through the command line it fails, the ticks over the variable fix that

Upvotes: 4

Related Questions