Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 765
user1058359 Avatar asked Nov 25 '15 23:11

user1058359


2 Answers

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'
like image 100
Moon Avatar answered Nov 11 '22 00:11

Moon


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

like image 45
user1058359 Avatar answered Nov 11 '22 01:11

user1058359