Run SQL Server Queries and Scripts with sqlcmd
sqlcmd gives you a small command-line entry point for inspecting a SQL Server instance and running repeatable scripts. Use it in place of old osql recipes. The examples below use Windows authentication and avoid placing a password in shell history.
Check the Client and Target
Install a supported sqlcmd package from Microsoft's documentation. Both Go and ODBC variants exist, and some options differ. Check the installed client's help before adding encryption flags.
sqlcmd -?
sqlcmd -S '.\SQLEXPRESS' -E -d master -Q "SELECT @@SERVERNAME AS ServerName, DB_NAME() AS DatabaseName;"
Replace .\SQLEXPRESS with your actual instance. Uppercase -S selects a server. Lowercase -s selects an output separator, which makes it an easy typo to overlook. A successful query returns the instance name and master.
Execute an Interactive Batch
sqlcmd -S '.\SQLEXPRESS' -E -d master
At the numbered sqlcmd prompt, enter:
SELECT DB_NAME() AS DatabaseName;
GO
GO asks the client to send the accumulated batch. It is not a Transact-SQL statement. Enter QUIT to leave. Do not put GO inside a -Q query string.
Run a File and Check Failure
Save this read-only script as inspect.sql:
SET NOCOUNT ON;
SELECT name, state_desc
FROM sys.databases
ORDER BY name;
GO
Execute it from PowerShell:
sqlcmd -S '.\SQLEXPRESS' -E -d master -b -i '.\inspect.sql'
if ($LASTEXITCODE -ne 0) {
throw "sqlcmd failed with exit code $LASTEXITCODE"
}
The result lists databases visible to your login. -b makes qualifying SQL errors fail the process, allowing a script runner to stop rather than treating an error message as success.
Resolve Authentication and Certificate Errors
Use an account granted only the required database permissions. If SQL authentication is necessary, use -U and the interactive password prompt rather than a literal -P password. Encryption defaults and -N syntax depend on the client version. Configure a trusted server certificate with the correct host name instead of routinely bypassing validation with -C.
Microsoft References
Author: Herman Schoenfeld