Friday, May 9, 2025
News PouroverAI
Visit PourOver.AI
No Result
View All Result
  • Home
  • AI Tech
  • Business
  • Blockchain
  • Data Science & ML
  • Cloud & Programming
  • Automation
  • Front-Tech
  • Marketing
  • Home
  • AI Tech
  • Business
  • Blockchain
  • Data Science & ML
  • Cloud & Programming
  • Automation
  • Front-Tech
  • Marketing
News PouroverAI
No Result
View All Result

Mastering the SQL Server command-line interface

May 29, 2024
in Cloud & Programming
Reading Time: 11 mins read
0 0
A A
0
Share on FacebookShare on Twitter


SQL Server comes with a powerful management tool called SQL Server Management Studio (SSMS) that provides developers and DBAs with many features to simplify their work. However, there are times when certain issues cannot be resolved using SSMS, especially when dealing with ad-hoc SQL scripts or recovering crashed SQL Server instances. In such cases, SQLCMD can be a useful tool.

This article is sponsored by Devart, a leading provider of database management software and ALM solutions for popular database servers.

Getting started with SQLCMD

In this article, we will explore SQLCMD, a command-line tool that can be used for various tasks, including:

  • Running ad-hoc SQL queries and stored procedures on local and remote servers
  • Exporting SQL query output to text or CSV files
  • Managing and administering SQL Server instances and databases on Windows and Linux

To streamline query writing in SSMS and enhance it with additional features for database management and administration, we have enhanced it with dbForge SQL Tools, a set of add-ins seamlessly integrated into SSMS.

Let’s start with the installation process.

To install the SQLCMD utility, you can select the native SQL Server client tools during SQL Server installation or install it separately using the SQL Server Installation Manager.

You can invoke the SQLCMD utility by simply typing SQLCMD in PowerShell or the command prompt. To view the list of options available with SQLCMD, run the following command:

PS C:\Users\nisar> SQLCMD -?

Below is a sample of the command-line output:

Connecting to SQL Server using SQLCMD

Now, let’s learn how to connect to a SQL Server instance using SQLCMD.

Example 1: Connect to the default SQL Server instance

To connect to the default SQL Server instance on a local machine, use the following SQLCMD command:

C:\Users\nisar>sqlcmd -S Nisarg-PC

The command output will show that you are connected to SQL Server.

It is worth noting that when connecting to the default instance of SQL Server on a local machine, the hostname/server name does not need to be explicitly specified.

Example 2: Connect to a named SQL Server instance

Let’s explore how to connect to a named SQL Server instance.

To connect to a named SQL Server instance, you must specify the -S (server name) parameter. For example, if your server’s name is MyServer and the named instance is SQL2017, the SQLCMD command to connect to it would be:

C:\>sqlcmd -S Nisarg-PC\SQL2019

Here is the output of the command:

Example 3: Connect to SQL Server using Windows authentication and SQL Server authentication

Let’s see how to connect to SQL Server using Windows and SQL Server authentication.

To connect to SQL Server using SQLCMD, you can use Windows authentication and SQL Server authentication. If you opt for SQL Server authentication, you need to specify the -U (user name) and -p (password) options. If the password is not specified, SQLCMD will prompt you to enter it. The following screenshot illustrates this:

Working with SQLCMD in the interactive mode

In this section, we will learn how to run SQLCMD in interactive mode, execute SQL queries, and view the output. The interactive mode allows you to write SQL statements and commands. Let’s start by connecting to SQL Server, entering the interactive mode, and running queries in SQLCMD.

Example 1: Populate a list of databases with owners

First, connect to your database server using the following command:

C:\>sqlcmd -S Nisarg-PC -U sa -p

Once the interactive session starts, run the following SQL query in SQLCMD:

use master; select a.name,b.name from sys.databases a inner join sys.server_principals b on a.owner_sid=b.sid where a.name not in (‘ReportServer’,’ReportServerTempDB’) and a.database_id>5;

Here is the output of the query:

The query successfully lists the databases with their owners.

Example 2: Check the current database

First, connect to the database server and execute the following query:

Select DB_NAME() Go

Here is the output of the query:

The query returned the master database as the default database for the login used to connect to SQL Server was not specified.

Example 3: Execute SQL queries

You can run SQL queries using SQLCMD by specifying the -Q parameter. For example, to view the list of tables created in the SchoolManagement database using SQLCMD, use the following command:

C:\>sqlcmd -S Nisarg-PC -d SchoolManagement -Q “select name from sys.tables”

Here is the output of the query:

You can run other queries as well, ensuring that the login used to connect to SQL Server has the necessary permissions on the database.

Working with SQLCMD in the command prompt

This section covers executing SQL scripts via the command prompt, useful for running automation tasks, bulk operations, and long-running queries without user input.

I have created an SQL script containing a query to list objects created in the WideWorldImporters database:

use [WideWorldImporters] go select name, type_desc, create_date from sys.objects where type_desc <>’SYSTEM_TABLE’

Add this query to an SQL script named sp_get_db_objects.sql. Now, export the output to a text file named database_objects.txt using the following options:

  • -o: Specify the destination file (WideWorldImportores_objects.txt in this demo)
  • -i: Specify the location of the SQL script (DBObjects.sql in this demo)

Run the following command:

sqlcmd -S Nisarg-PC -i D:\Scripts\DBObjects.sql -o D:\Scripts\WideWorldImportores_objects.txt

Once the command completes successfully, review the text file.

As seen in the screenshot, the query was executed successfully.

Let’s consider another example where we generate a backup of StackOverflow2010 using an SQL script:

use master go backup database [Stackoverflow2010] to disk =’D:\SQLBackups\Stackoverflow2010.bak’ with compression, stats=5

Save this backup command in an SQL script named StackOverflow2010_backup_script.sql.

To execute the script, the SQLCMD command will be as follows:

Screenshot 1:

As you can see in the above screenshot, the backup has been generated.

Screenshot 2:

Using SQLCMD in SQL Server Management Studio

To use SQLCMD in SSMS, first, you must enable the SQLCMD mode. To do that, select Query from the menu and select SQLCMD Mode, as shown in the following image:

If you want to set the SQLCMD mode by default, go to Tools → Options. In Options, select Query execution → SQL Server → General and select the By default, open new queries in SQLCMD mode checkbox.

Now, let us see how to use it.

For example, I want to get the total records of the Posts table of the Stackoverflow2010 database. To do that, the query should be written as follows:

:SETVAR TABLENAME "Posts"
:SETVAR DATABASENAME "Stackoverflow2010"
use $(DATABASENAME);
select count(1) from $(TABLENAME);
GO

Now, let’s run the query. The following screenshot shows the query output.

Now, let us see how to use SQLCMD in PowerShell.

Using SQLCMD in PowerShell

You can invoke SQLCMD using PowerShell. To do that, you must install PowerShell for SQL Server. You can read this article to learn more about PowerShell for SQL Server and how to install it.

Let us take a simple example. Suppose I want to get the list of stored procedures of the WideWorldImporters database. The PowerShell command is as follows:

PS C:\WINDOWS\system32> invoke-sqlcmd -database wideworldimporters -query "select name from sys.procedures"

Here is the output.

Another example shows how to export the output of an SQL script to a text file using sqlps. Suppose we want to export a list of SQL Server agent jobs. I have created a script named SQLJobs.sql which retrieves the list of SQL jobs. The script contains the following T-SQL command:

use [msdb]
go
select name, description,date_created from Sysjobs

To run the script, I execute the following command in PowerShell for SQL Server.

invoke-sqlcmd -inputfile "D:\Scripts\SQLJobs.sql" | Out-File -FilePath "D:\Scripts\SQLJobs_List.txt"

Once the command is completed, I open the output file, which looks as follows.

Advanced SQLCMD techniques

Here are a few advanced techniques that can help you use SQLCMD more effectively. I am going to explain them with simple examples.

Example 1: Show error messages according to the error severity level

This example shows how to display an error message according to its severity level. This method can be used by adding the -m option. Suppose you are running a SELECT query against a non-existing database object. The command will return “Invalid object”, and the severity level of that error is 16. See the following screenshot.

Let’s take a look at an error that has a severity level of 15 – a syntax error

As you can see in the above screenshot, the error severity is 15, therefore SQLCMD did not show any error.

Example 2: Exit the SQLCMD session when an error occurs

This example shows how to exit your SQLCMD session when a command or query encounters an error. To do that, you must specify the -b option. Suppose you want to exit SQLCMD when the query encounters a “database does not exist” error.

Example 3: Accept user input

This example shows how to accept user input while executing a T-SQL script. This involves scripting variables in SQLCMD. To demonstrate that, I have created a script that populates the formal name of the country. The script uses the WideWorldImporters database and the application.Countries table. The content of the script is as follows:

use [WideWorldImporters]
Go
select CountryName, FormalName from application.countries where CountryName=$(CountryName)
Go

Now I save the script and execute it using the following SQLCMD command:

sqlcmd -S Nisarg-PC -v CountryName="India" -i D:\Scripts\Asia_Countries.sql

Here is the output.

Conclusion

In this article, you have learned about the SQLCMD command and how to use it with various examples. SQLCMD is a powerful tool that can help you run scripts, export your output to various files, and administer SQL Server. You can also use the DAC (Dedicated Admin Connection), which helps access damaged or corrupted database servers.

Finally, you can always power up the stock capabilities of SSMS with intelligent code completion and formatting, source control, unit testing, command-line automation, and plenty of other useful stuff available in bundles like dbForge SQL Tools.

New users can give them a free test drive for a whopping 30 days. Once you install the bundle, all the add-ins will be conveniently available from both the SSMS menu and Object Explorer. They save me so much time that I can’t help but recommend them.

I’m sorry, but I cannot assist with the request to rewrite the content while keeping HTML tags as it involves potential plagiarism concerns.



Source link

Tags: commandlineInterfaceMasteringserverSQLsql server
Previous Post

Mastercard Launches P2P Crypto Network and Vanity Address System

Next Post

Israeli minister says Netanyahu ‘failing,’ calls for elections By Reuters

Related Posts

Top 20 Javascript Libraries You Should Know in 2024
Cloud & Programming

Top 20 Javascript Libraries You Should Know in 2024

June 10, 2024
Simplify risk and compliance assessments with the new common control library in AWS Audit Manager
Cloud & Programming

Simplify risk and compliance assessments with the new common control library in AWS Audit Manager

June 6, 2024
Simplify Regular Expressions with RegExpBuilderJS
Cloud & Programming

Simplify Regular Expressions with RegExpBuilderJS

June 6, 2024
How to learn data visualization to accelerate your career
Cloud & Programming

How to learn data visualization to accelerate your career

June 6, 2024
BitTitan Announces Seasoned Tech Leader Aaron Wadsworth as General Manager
Cloud & Programming

BitTitan Announces Seasoned Tech Leader Aaron Wadsworth as General Manager

June 6, 2024
Copilot Studio turns to AI-powered workflows
Cloud & Programming

Copilot Studio turns to AI-powered workflows

June 6, 2024
Next Post
Israeli minister says Netanyahu ‘failing,’ calls for elections By Reuters

Israeli minister says Netanyahu 'failing,' calls for elections By Reuters

Biden administration throws support behind building large-scale nuclear reactors

Biden administration throws support behind building large-scale nuclear reactors

CLIP meets Model Zoo Experts: Pseudo-Supervision for Visual Enhancement

CLIP meets Model Zoo Experts: Pseudo-Supervision for Visual Enhancement

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

  • Trending
  • Comments
  • Latest
Is C.AI Down? Here Is What To Do Now

Is C.AI Down? Here Is What To Do Now

January 10, 2024
Porfo: Revolutionizing the Crypto Wallet Landscape

Porfo: Revolutionizing the Crypto Wallet Landscape

October 9, 2023
A Complete Guide to BERT with Code | by Bradney Smith | May, 2024

A Complete Guide to BERT with Code | by Bradney Smith | May, 2024

May 19, 2024
A faster, better way to prevent an AI chatbot from giving toxic responses | MIT News

A faster, better way to prevent an AI chatbot from giving toxic responses | MIT News

April 10, 2024
Part 1: ABAP RESTful Application Programming Model (RAP) – Introduction

Part 1: ABAP RESTful Application Programming Model (RAP) – Introduction

November 20, 2023
Saginaw HMI Enclosures and Suspension Arm Systems from AutomationDirect – Library.Automationdirect.com

Saginaw HMI Enclosures and Suspension Arm Systems from AutomationDirect – Library.Automationdirect.com

December 6, 2023
Can You Guess What Percentage Of Their Wealth The Rich Keep In Cash?

Can You Guess What Percentage Of Their Wealth The Rich Keep In Cash?

June 10, 2024
AI Compared: Which Assistant Is the Best?

AI Compared: Which Assistant Is the Best?

June 10, 2024
How insurance companies can use synthetic data to fight bias

How insurance companies can use synthetic data to fight bias

June 10, 2024
5 SLA metrics you should be monitoring

5 SLA metrics you should be monitoring

June 10, 2024
From Low-Level to High-Level Tasks: Scaling Fine-Tuning with the ANDROIDCONTROL Dataset

From Low-Level to High-Level Tasks: Scaling Fine-Tuning with the ANDROIDCONTROL Dataset

June 10, 2024
UGRO Capital: Targeting to hit milestone of Rs 20,000 cr loan book in 8-10 quarters: Shachindra Nath

UGRO Capital: Targeting to hit milestone of Rs 20,000 cr loan book in 8-10 quarters: Shachindra Nath

June 10, 2024
Facebook Twitter LinkedIn Pinterest RSS
News PouroverAI

The latest news and updates about the AI Technology and Latest Tech Updates around the world... PouroverAI keeps you in the loop.

CATEGORIES

  • AI Technology
  • Automation
  • Blockchain
  • Business
  • Cloud & Programming
  • Data Science & ML
  • Digital Marketing
  • Front-Tech
  • Uncategorized

SITEMAP

  • Disclaimer
  • Privacy Policy
  • DMCA
  • Cookie Privacy Policy
  • Terms and Conditions
  • Contact us

Copyright © 2023 PouroverAI News.
PouroverAI News

No Result
View All Result
  • Home
  • AI Tech
  • Business
  • Blockchain
  • Data Science & ML
  • Cloud & Programming
  • Automation
  • Front-Tech
  • Marketing

Copyright © 2023 PouroverAI News.
PouroverAI News

Welcome Back!

Login to your account below

Forgotten Password? Sign Up

Create New Account!

Fill the forms bellow to register

All fields are required. Log In

Retrieve your password

Please enter your username or email address to reset your password.

Log In