Trouble connecting to localdb via SQLCMD in PowerShell - what is server instance name?

百般思念 提交于 2019-12-25 03:34:52

问题


SQL Server newbie here - I'm trying to access the localdb\MSSQLLocalDB server on my computer through PowerShell with the SQLCMD utility. I'm using PowerShell v5, .NET v5.0, and The server name is (localdb)\MSSQLLocalDB when I connect to it in Microsoft SQL Server Management Studio 2014.

PS C:\> sqlcmd -S localdb\MSSQLLocalDB and PS C:\> sqlcmd -S .\localdb\MSSQLLocalDB result in this error:

Sqlcmd: Error: Microsoft ODBC Driver 11 for SQL Server : SQL Server Network Interfaces: Error Locating Server/Instance Specified [xFFFFFFFF].

I queried the server name in Management Studio with SELECT @@ServerName and used that after the -S in the above command and got the same error.

PS C:\> sqlcmd -S localdb gives this error:

Sqlcmd: Error: Microsoft ODBC Driver 11 for SQL Server : Named Pipes Provider: Could not open a connection to SQL Server [53]

Other notes: I'm able to connect to the server and work with a database named testdb01 in a C# console app using System.Data.SqlClient with this connection string:

"Data Source=(localdb)\\mssqllocaldb;Initial Catalog=testdb01;Integrated Security=SSPI;"

Any ideas on where to start or how to approach this?


回答1:


Passing arguments from PowerShell to EXEs can be tricky. I think you need to escape the parens either with single quotes, which means the content is a static literal string, or the backtick escape character:

sqlcmd -S '(localdb)\MSSQLLocalDB' -Q "Select @@servername"

sqlcmd -S `(localdb`)\MSSQLLocalDB -Q "Select @@servername"

or even using a variable:

PS H:\> $myserver = '(localdb)\MSSQLLocalDB'

PS H:\> sqlcmd -S $myserver -Q "Select @@servername"

Also, if you are using sqlcmd, perhaps look at Invoke-Sqlcmd which is more native to PowerShell:

PS SQLSERVER:\> Invoke-Sqlcmd -Server $myserver -Query "Select @@servername"


来源:https://stackoverflow.com/questions/34457048/trouble-connecting-to-localdb-via-sqlcmd-in-powershell-what-is-server-instance

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!