求助:通过CMD执行.sql文件出错(已安装ODBC Driver 13.1)
sqlcmd Execution Error Let’s walk through the most likely issues with your command and how to fix them:
1. LocalDB Instance Name or Availability Issue
First, double-check if your LocalDB instance is correctly named and running:
- Run
sqllocaldb infoin CMD to list all existing LocalDB instances. If you don’t seemyDBin the output, your instance name is wrong (the default LocalDB instance is usuallyMSSQLLocalDB). Update the-Sparameter to match the correct instance name. - If the instance exists but isn’t running, start it first with
sqllocaldb start myDB(replacemyDBwith your actual instance name) before running yoursqlcmdcommand.
2. Authentication Mismatch
LocalDB is configured to use Windows Authentication by default, but your command includes -U user -P password which specifies SQL Server Authentication. This is a common conflict:
- If you haven’t explicitly enabled SQL Authentication for your LocalDB instance, remove the
-Uand-Pparameters entirely. Your command will then use your current Windows user account to connect. - If you need to use SQL Authentication, first connect to your LocalDB instance via SSMS, enable SQL Server Authentication, and create a valid login/user with the necessary database permissions.
3. Invalid SQL File Path
Verify that the path to your .sql file is correct:
- Run
dir "C:\PathToMyFile\File.sql"in CMD to confirm the file exists. If this command returns "File not found", fix the path or filename spelling. - Even though you’ve wrapped the path in quotes (which is correct for paths with spaces), ensure there are no typos or special characters causing issues.
4. sqlcmd and ODBC Driver Compatibility
While you have ODBC Driver 13.1 installed, older versions of sqlcmd might not properly interface with it:
- Run
sqlcmd -?to check your currentsqlcmdversion. If it’s outdated, install the latest SQL Server Command Line Tools—this package includes an updatedsqlcmdthat works seamlessly with modern ODBC drivers.
5. Permission Problems
Make sure you have the right permissions:
- The user running CMD needs read access to the
.sqlfile. - Your authentication account (Windows or SQL) must have sufficient permissions on the target LocalDB database (e.g.,
CREATE TABLE,EXECUTE, etc., depending on what your.sqlfile does).
Example Test Command
If you’re using the default LocalDB instance and Windows Authentication, try this simplified command first to rule out issues:
sqlcmd -e -S "(localdb)\MSSQLLocalDB" -i "C:\PathToMyFile\File.sql"
内容的提问来源于stack exchange,提问作者Emile

