Search code examples
sqlsqlcmd

sqlcmd how to run a query against specific database?


so this is the query that i want to run

sqlcmd -E -S localhost\MSSQLSERVER_2016 -i C:\Tables.sql

I have multiple databases in this instance and when the command above runs, i have no idea which database it runs the query against. Is there any way that i can use sqlcmd to run against a database that i want it to run?

i have also tried

sqlcmd -E -S localhost\MSSQLSERVER_2016.mydatabase -i C:\Tables.sql

but that didn't work.


Solution

  • Use the -d command line option to specify your database.

    Link to the docs.

    -d db_name

    Issues a USE <db_name> statement when you start sqlcmd. This option sets the sqlcmd scripting variable SQLCMDDBNAME. This parameter specifies the initial database. The default is your login's default-database property. If the database doesn't exist, an error message is generated and sqlcmd exits.