Dave
Dave

Reputation: 19280

How to I run a single sql command from the sqlcmd prompt?

In SQL Server, if I want to run a script from the command line, I can do this

/opt/mssql-tools/bin/sqlcmd -S $DB_HOST -U $DB_USER -P $DB_PASS -d $DB_NAME -i myscript.sql

Is it possible to run just a single command without a script and get the results? For instance, if I just wanted to run

SELECT 1

How would I do that from the command line?

Upvotes: 4

Views: 16916

Answers (2)

nam20485
nam20485

Reputation: 353

Given that you want to:

run just a single command without a script and get the results

Another possible answer would be to run:

sqlcmd -S localhost -U MyUser -P MyPass -d MyDb -Q "SELECT 1"

That is with a capital -Q.

This will run the command and then exit, allowing you to read the error code result.

The answer above uses lowercase -q, which will run the command but leave the sqlcmd prompt open and running.

Depending on what you want, the case of the -Q/-q argument matters.

Documentation reference.

Upvotes: 3

SE1986
SE1986

Reputation: 2760

I think you want the -q switch:

sqlcmd -S localhost -U MyUser -P MyPass -d MyDb -q "SELECT 1"

Documentation is here

Upvotes: 6

Related Questions