简体   繁体   中英

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!

解决方案是执行SET @dbname = '$(databaseName)'而不是SET @dbname = $(databaseName)它可以在实际的查询程序中使用,但是通过命令行失败,在变量fix上打勾

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'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM