User Tools

Site Tools


apps:mssql:sqlcmd

MSSQL - sqlcmd

Example Environment

DescriptionValue
Hostname / Container Namemssqlsrv
MSSQL Usersa
MSSQL User sa PasswordjeWzuQ7ZRRmH
MSSQL Port1433

Connect

sqlcmd -S "mssqlsrv,1433" -U "sa" -P "jeWzuQ7ZRRmH" -y 30 -Y 30

Run as Docker Container

Microsoft provides the mcr.microsoft.com/mssql-tools Docker image which contains sqlcmd.

Pull the image

docker pull mcr.microsoft.com/mssql-tools

Create a container with this image and enter the shell.

docker run -it mcr.microsoft.com/mssql-tools

In the container you can use the sqlcmd

root@server:~# docker run -it mcr.microsoft.com/mssql-tools
root@192e24c47a64:/# sqlcmd -S "mssqlsrv,1433" -U "sa" -P "jeWzuQ7ZRRmH" -y 30 -Y 30
1> 

Use the –net parameter to make sure, sqlcmd can connect to your MSSQL container.

docker run -it --net container:mssqlsrv mcr.microsoft.com/mssql-tools

You can also create the container and connect with sqlcmd in a single command

docker run -it --net container:mssqlsrv mcr.microsoft.com/mssql-tools /opt/mssql-tools/bin/sqlcmd -S "mssqlsrv,1433" -U "sa" -P "jeWzuQ7ZRRmH" -y 30 -Y 30
1>

Queries

With the keyword GO on a single line, a line ending is indicated.

List Databases

SELECT name, database_id, create_date FROM sys.databases;
GO
1> SELECT name, database_id, create_date FROM sys.databases;
2> GO
name                         database_id create_date
---------------------------- ----------- -----------------------
master                                 1 2003-04-08 09:13:36.390
tempdb                                 2 2024-08-14 08:28:02.960
model                                  3 2003-04-08 09:13:36.390
msdb                                   4 2024-07-10 14:43:42.733
Customers                              5 2024-07-31 07:10:39.220

(5 rows affected)
1>

Create a Database with a Table

Create Database

Switch to the master database context and create a new database. CREATE DATABASE

USE master;
GO
CREATE DATABASE Company;
GO

Switch to Database Context

Switch to the database context with USE.

USE Company;
GO

Create Table

Create a basic table. CREATE TABLE

CREATE TABLE Employees (
    EmployeeID INT PRIMARY KEY,
    FirstName NVARCHAR(50),
    LastName NVARCHAR(50),
    HireDate DATE
);
GO

Add Records

Add two records to the table. INSERT

INSERT INTO Employees (EmployeeID, FirstName, LastName, HireDate)
VALUES (1, 'John', 'Doe', '2024-08-01');
GO
INSERT INTO Employees (EmployeeID, FirstName, LastName, HireDate)
VALUES (2, 'Jane', 'Doe', '2024-08-18');
GO

Delete Table

DROP TABLE

DROP TABLE Employees;
GO;

Delete Database

DROP DATABASE

DROP DATABASE Company;
GO

Show Server Version

SELECT @@VERSION AS 'Server Version';
GO
1> SELECT @@VERSION As 'Server Version';
2> GO
Server Version                
------------------------------
Microsoft SQL Server 2022 (RTM

(1 rows affected)
apps/mssql/sqlcmd.txt · Last modified: 2024-10-02 16:33 by Manuel Frei