Sie sind auf Seite 1von 22

SQL Server on Linux for SQL Server

Administrators
Hands-on Lab Manual

Published: January 2017

Applies to: Microsoft SQL Server 2017 for Linux

Summary: SQL Server on Linux will provide customers with even more flexibility in their data solution.
Built on SQL Server 2017, SQL Server on Linux gives the power to build and deploy intelligent applications
on a single data management and business analytics platform—one with mission-critical performance,
industry-leading TCO, best-in-class security, and hybrid cloud innovations all built in.

Page 1
Copyright
The information contained in this document represents the current view of Microsoft Corporation on the
issues discussed as of the date of publication. Because Microsoft must respond to changing market
conditions, it should not be interpreted to be a commitment on the part of Microsoft, and Microsoft
cannot guarantee the accuracy of any information presented after the date of publication.

This white paper is for informational purposes only. MICROSOFT MAKES NO WARRANTIES, EXPRESS,
IMPLIED, OR STATUTORY, AS TO THE INFORMATION IN THIS DOCUMENT.

Complying with all applicable copyright laws is the responsibility of the user. Without limiting the rights
under copyright, no part of this document may be reproduced, stored in, or introduced into a retrieval
system, or transmitted in any form or by any means (electronic, mechanical, photocopying, recording, or
otherwise), or for any purpose, without the express written permission of Microsoft Corporation.

Microsoft may have patents, patent applications, trademarks, copyrights, or other intellectual property
rights covering subject matter in this document. Except as expressly provided in any written license
agreement from Microsoft, the furnishing of this document does not give you any license to these
patents, trademarks, copyrights, or other intellectual property.

© 2017 Microsoft Corporation. All rights reserved.

Microsoft, Active Directory, Microsoft Azure, Excel, SharePoint, SQL Server, Windows, and Windows Server
are trademarks of the Microsoft group of companies.

All other trademarks are property of their respective owners.

Page 2
Contents
Contents ......................................................................................................... 3

Overview ......................................................................................................... 4

Getting familiar with the Linux operating system ............................................. 5

Installing the mssql-server Package ................................................................ 6

Requirements for package installation .....................................................................................6

Installation – Red Hat Enterprise Linux.....................................................................................7

Installation steps - Ubuntu ....................................................................................................10

Update/upgrade steps (optional) ................................................................... 14

Run and connect to SQL Server on Linux ........................................................ 14

View service status ................................................................................................................14

Stop and start the service ......................................................................................................14

Check the SQL Server version .................................................................................................15

Using sqlcmd: quick reference ...............................................................................................15

Set up a sample database .............................................................................. 17

Install AdventureWorks ..........................................................................................................17

Basic tasks .................................................................................................... 18

Query tables ..........................................................................................................................18

Execute a stored procedure ...................................................................................................19

Update a record .....................................................................................................................19

Bulk Insert .............................................................................................................................19

Summary and conclusion ............................................................................... 21

Page 3
Overview
Note: Estimated time to complete lab is 30–45 minutes.

Microsoft has announced its plans to bring SQL Server to Linux. This will enable SQL Server to deliver a
consistent data platform across Windows Server and Linux, as well as on-premises and cloud. SQL Server
on Linux will provide customers with even more flexibility in their data solution. Built on SQL Server 2017,
SQL Server on Linux gives the power to build and deploy intelligent applications on a single data
management and business analytics platform—one with mission-critical performance, industry-leading
TCO, best-in-class security, and hybrid cloud innovations all built in. This will let customers access their
data on-premises and in the cloud whenever they want at low cost.

This lab was built based on the features and functionality available in the initial public preview release,
SQL Server for Linux. As the Microsoft team continues toward general availability of SQL Server, users can
expect to see additional features and capabilities in later releases of the product.

This manual will guide you through the steps to setting up SQL Server on Linux along with the command-
line tools and ODBC drivers. In this exercise, you will:

• Become familiar with basic operations within a Linux terminal session and the local file
system

• Successfully install SQL Server using the native package manager (yum for Red Hat, apt
for Ubuntu)

• Successfully install SQL Server command-line tools (sqlcmd) and ODBC drivers using the
native package manager

• Learn how to check for system updates and install updates using the native package
manager

• Learn how to verify the SQL Server service (mssql-server) is running, as well as how to
start/stop the service, and how to enable or disable the service to start automatically

• Learn how to restore a database backup using a sample database backup from the local
file system

• Learn how to back up a database to the local file system

• Using the command-line tools, perform basic functions using TSQL commands

• Using the command-line tool, perform basic functions using .sql script files on the local
file system

• Using the command-line tool, output query/command result to a file in the local system
and, using grep, search the output file using regular expressions

Note: Each command in this document begins with either a $ or # which represents the terminal prompt.
Please copy the entire command even if the command wraps to the next line.

Page 4
Getting familiar with the Linux
operating system
Note: This section is intended to help those new to Linux understand the interface and environment at a
basic level. If you have previous experience with Red Hat or Ubuntu systems, you may want to skip this
section and move to “Installing the mssql-server package.”

The tasks in this lab require actions be performed from a terminal session using command-line
instructions. The virtual machines, which are accompanied by this manual, are running an installation of
Linux without the graphical user interface. If you are using your own environment that includes a
graphical interface, you will need to open a terminal session.

Sudo and su: It is a best practice to limit the use of “root” (synonymous with “Administrator”) logins to
those cases in which it is absolutely required. In the event that a user needs to perform an administrative
task involving restricted command, files, or directories, users temporarily “elevate” their permissions to
perform that task. Calling “sudo” before a command elevates permissions for that single command. The
user will be asked for their password the first time sudo is invoked in a session.

In the above example, attempting to create a directory named “foo” in the restricted directory “/var/opt”
results in an error. The same command with “sudo” invoked succeeds after password verification.

Entering “sudo su” runs all commands in the command prompt as “root” until the user types “exit”. Note
that the prompt shows the current user as “root” after password verification, and it reverts to “labuser”
after exiting.

File systems are different in Linux compared to Windows. For the purposes of this lab, you will need to
understand a few basic concepts:

Page 5
• System directories such as “boot,” “dev,” “etc,” “mnt,” and so forth should not be
modified without express intent.

• “Home” is the user’s home directory (located under “/home/[user name]”) and is
generally where users will store their data. Other users (except root) will not be able to
view or change another user’s home directory.

• Users will note that directory separators are forward slashes (“/”) not back slashes (“\”).

• Linux does not use drive letters. The file system begins with root “/” and additional
volumes, such as removable media or hard discs, are defined in “/dev” and accessed in
“/mnt” (after being mounted).

• Linux files and directories are managed using “chmod,” short for change modifier, and
ownership of files is managed using “chown,” short for change owner. Note that chmod
and chown are not a part of daily use for a user, and they can seriously impact a system
if used improperly. As a part of the SQL Server preview, you will be modifying files as a
part of the installation process. For more information about chmod and chown, please
refer to the documentation provided by your Linux distributor.

Installing the mssql-server Package


Note: There is a 180-day trial period in the engine.

Requirements for package installation


• Red Hat Enterprise Linux 7.2, Ubuntu 16.04 LTS

Can be deployed in either a Minimal Server (terminal only) or within a GUI enabled
installation with Terminal.

• Minimum of 4 GB of RAM

• Minimum of 4 GB of disk space

• XFS (default on RHEL) or EXT4 (default on Ubuntu) file system

• TCP port 1433 open on the firewall for SQL Server connections

• Network connectivity to the Internet to download the package

Additional notes:

• firewalld is a recommended package and for the purposes of our lab will be installed
prior to beginning installation.

• dos2unix is a required package and for the purposes of our lab will be installed prior to
beginning installation.

Login info:

Login: labuser

Page 6
Password: Pass@word1

Installation – Red Hat Enterprise Linux


Configure the distribution repository
1. Add the repo information for mssql-server to /etc/yum.repos.d/
$ sudo su
# sudo curl -o /etc/yum.repos.d/mssql-server.repo
https://packages.microsoft.com/config/rhel/7/mssql-server-2017.repo
# exit

Install MS SQL Server on Linux


2. Install the mssql-server package.
$ sudo yum install -y mssql-server

Page 7
After installation on Linux, you will need to do the following to accept the license agreement and provide
the system administrator (SA) password.

3. Run the configuration script to accept the license agreement and provide the System
Administrator (SA) password.
$ sudo /opt/mssql/bin/mssql-conf setup

You should be prompted to allow SQL Server Service to start and Enable SQL Server Service to start on
boot. If you are not, you can enable and start the SQL Server service using the following commands.
$ sudo systemctl enable mssql-server
$ sudo systemctl start mssql-server
4. You will need to open a port on the firewall. If you are using firewalld as your firewall,
you can use these commands:

Page 8
$ sudo firewall-cmd --zone=public --add-port=1433/tcp --permanent
$ sudo firewall-cmd --reload

5. Verify that the package was installed.


$ rpm -qa | grep mssql

Note: The current release also includes the package mssql-conf. You can run /opt/mssql/bin/mssql-conf
to learn more.

Install the command-line tools and ODBC drivers


The Command Line Utilities for SQL Server (SQLCMD and BCP utilities) are in private preview and
available for Red Hat Enterprise Linux 7.2. and Ubuntu 16.04. The SQLCMD utility allows users to connect
to, send Transact-SQL batches from, and output rowset information from SQL Server instances. The BCP
utility bulk copies data between an instance of Microsoft SQL Server and a data file in a user-specified
format. Installing these utilities will also install the Microsoft ODBC driver and all its dependencies by
default. To install these tools, run the following commands as detailed in the terminal:

The command-line tools (SQLCMD and BCP) can also be installed on Red Hat Enterprise Linux through
the Microsoft ODBC drivers package. Please use the following installation script to simplify the process,
the script can be downloaded and run by following the steps below:

6. Add the repo information for mssql-tools to /etc/yum.repos.d/


$ sudo su
# sudo curl -o /etc/yum.repos.d/msprod.repo
https://packages.microsoft.com/config/rhel/7/prod.repo
# exit
7. If you had a previous version of mssql-tools installed, remove any older unixODBC
packages.
$ sudo yum remove unixODBC-utf16 unixODBC-utf16-devel

8. Install the mssql-tools package.


$ sudo yum -y install mssql-tools unixODBC-devel

9. Update the PATH environment variable


echo 'export PATH="$PATH:/opt/mssql-tools/bin"' >> ~/.bash_profile
echo 'export PATH="$PATH:/opt/mssql-tools/bin"' >> ~/.bashrc
source ~/.bashrc

Page 9
10. You should now be able to call the “sqlcmd” and “bcp” commands:
$ sqlcmd -H <hostname> -U <username> -P <password>
11. To exit the prompt, type quit.
1> quit

Installation steps - Ubuntu


Configure the distribution repository

12. Please ensure your system is fully updated using the below commands prior to
installation, to ensure greatest system stability.
$ sudo apt-get update
$ sudo apt-get upgrade

13. Browse to the scripts within the user’s home directory.


$ cd /home/labuser/scripts

14. Add the repo information for mssql-server to /etc/apt/sources.list.d/


$ sudo su

# wget -qO- https://packages.microsoft.com/keys/microsoft.asc | sudo apt-


key add -

Page 10
# sudo add-apt-repository "$(wget -qO-
https://packages.microsoft.com/config/ubuntu/16.04/mssql-server-
2017.list)"
# exit
15. Run the following commands to prepare the repository data for MS SQL Server.
$ sudo apt-get update

Install MS SQL Server on Linux


16. Install the mssql-server package.
$ sudo apt-get install -y mssql-server

After installation on Linux, you will need to do the following to accept the license agreement and provide
the system administrator (SA) password.

17. Run the configuration script to accept the license agreement and provide the System
Administrator (SA) password.
$ sudo /opt/mssql/bin/mssql-conf setup

You should be prompted to allow SQL Server Service to start and Enable SQL Server Service to start on
boot, if you are not, you can Enable and start the SQL Server service using the following commands:

Page 11
$ sudo systemctl enable mssql-server
$ sudo systemctl start mssql-server
18. You will need to open a port on the firewall If you are using firewalld as your firewall you
can use these commands.
$ sudo firewall-cmd --zone=public --add-port=1433/tcp --permanent $ sudo
firewall-cmd --reload

19. Verify that the package was installed.


$ dpkg-query -W | grep mssql

Note: the current release also includes the package mssql-conf, you can run /opt/mssql/bin/mssql-conf to
learn more.

Install the command-line tools and ODBC drivers


The Command Line Utilities for SQL Server (SQLCMD and BCP utilities) are in private preview and
available for Ubuntu 16.04 LTS. The SQLCMD utility allows users to connect to, send Transact-SQL batches
from, and output rowset information from SQL Server instances. The BCP utility bulk copies data between
an instance of Microsoft SQL Server and a data file in a user-specified format. Installing these utilities will
also install the Microsoft ODBC driver and all its dependencies by default. To install these tools, run the
following commands as detailed in the terminal.

20. Add the private preview tools repository, and install the SQL Command Line Utilities with
its dependencies by running the commands below.
$ sudo su
# curl https://packages.microsoft.com/config/ubuntu/16.04/prod.list >
/etc/apt/sources.list.d/ms-prod.list
# exit
21. Update the sources list and run the installation command.
$ sudo apt-get update
$ sudo apt-get install mssql-tools
22. When prompted about the license terms, read the terms and conditions, and then press
the tab key to select (i.e. highlight) <Yes>, and press ‘Enter’ key to continue.

Page 12
1. Update the PATH environment variable
$ echo 'export PATH="$PATH:/opt/mssql-tools/bin"' >> ~/.bash_profile
$ echo 'export PATH="$PATH:/opt/mssql-tools/bin"' >> ~/.bashrc
source ~/.bashrc

2. You should now be able to call the “sqlcmd” and “bcp” commands.
$ sqlcmd -H <hostname> -U <username> -P <password>
3. To exit the prompt, type quit.
1> quit

Page 13
Update/upgrade steps (optional)
Red Hat
For Red Hat, run the update command, followed by the install command. If there’s a newer package, it
will upgrade it.
$ sudo yum update
$ sudo yum install mssql-server

Ubuntu
For Ubuntu, run the install command as well.
$ sudo apt-get update
$ sudo apt-get install mssql-server

Run and connect to SQL Server on


Linux
View service status
SQL Server runs on Linux as a service that is started as a default after installation.

Use the following command to view the status of the SQL Server service.
$ sudo systemctl status mssql-server

Stop and start the service


Use the following command to stop the SQL Server service, and then check the status.
$ sudo systemctl stop mssql-server

Page 14
$ sudo systemctl status mssql-server

Note: The error here shows that the SQL Server is not running.

Use the following command to start the SQL Server service.


$ sudo systemctl start mssql-server
$ sudo systemctl status mssql-server

Check the SQL Server version


Use the following query to check the version of SQL on Linux that you are using.
$ sqlcmd -S localhost -U sa -P Pass@word1 -Q “SELECT @@VERSION AS ‘SQL
SERVER VERSION’;”

Using sqlcmd: quick reference


You can get detailed information on usage and parameters for sqlcmd.
$ sqlcmd -?

Page 15
For the purposes of this lab, we will regularly use the following parameters:
Parameter Description Use in this lab
-S Server or Dsn if -D is We will be using “localhost” with no instance
provided name, which will connect to the local machine’s
default SQL Server instance.
-d Use database name We will be using “AdventureWorks” for most
exercises, occasionally using “master” when
required
-U Login id This is the SQL login ID – in the case of this lab,
“sa”.
-P Password This is the sa password supplied during SQL
Server installation – in the case of this lab
“Pass@word1”
-Q “cmdline query” and exit Executes the string value as T-SQL instructions,
and exits sqlcmd when complete.
-q “cmdline query” Executes the string value as T-SQL instructions.
sqlcmd remains open until ‘quit’ is entered.
-i inputfile Reads the specified file into sqlcmd as stdin.
Sample script files (.sql) will be provided with the
lab environment, in the interest of reducing the
amount of typing required.
-o outputfile Writes output (stdout, stderr) to the specified
file. When dealing with very large output, we will
specify the output file and either view the file in
an editor, or provide a grep command to view
specific information.

Page 16
Set up a sample database
Install AdventureWorks
AdventureWorks is a sample database used in code examples in SQL Server Books Online and in
companion samples that can be downloaded from the Microsoft SQL Server Database Product Samples
home page. The database schema is designed to showcase SQL Server features.

The AdventureWorks OLTP database supports standard online transaction processing scenarios for a
fictitious bicycle manufacturer (Adventure Works Cycles). Scenarios include Manufacturing, Sales,
Purchasing, Product Management, Contact Management, and Human Resources.

The AdventureWorks DW database demonstrates how to build a data warehouse and is a simplified and
smaller sample database helpful for those new to relational database technology.

Note that the version of AdventureWorks for SQL Server 2016 is not supported for SQL Server on Linux
now because it exercises features that are not yet supported.

For the purposes of this lab, the AdventureWorks.bak file is pre-populated in the following directory:

/var/opt/mssql/data

Execute the T-SQL statements below to create the AdventureWorks database. Note that the virtual “C:\”
path maps to the root directory (/) for SQL Server in this preview release.

For example, “C:\var\opt\mssql\data\AdventureWorks2014.bak” is the way to specify a path to


“/var/opt/mssql/data/AdventureWorks2014.bak”. We will be addressing this path idiosyncrasy in a
future release. As of the current version you can use both pathways.

Execute the .sql script:


$ sqlcmd -S localhost -d master -U sa -P Pass@word1 -i
/home/labuser/scripts/Restore_AW2014_Database.sql

Or enter:
$ sqlcmd -S localhost -d master -U sa -P Pass@word1 -Q "RESTORE DATABASE
[AdventureWorks]
FROM DISK = N‘/var/opt/mssql/data/AdventureWorks2014.bak'
WITH MOVE 'AdventureWorks2014_Data' TO
N'/var/opt/mssql/data/AdventureWorks2014_Data.mdf',
MOVE 'AdventureWorks2014_Log' TO
N'/var/opt/mssql/data/AdventureWorks2014_Log.ldf';"

Page 17
Basic tasks
Query tables
The data types, schemas, stored procedures, and functions in AdventureWorks are documented here.

Execute the simple query below to list all departments and the groups they belong to.
$ sqlcmd -S localhost -d AdventureWorks -U sa -P Pass@word1 -Q "SELECT
TOP 20 Name, GroupName FROM HumanResources.Department;"

Entering a single line into sqlcmd is simple. However, larger sets of commands can be cumbersome. This
lab includes .sql script files, which can be called from sqlcmd with the “-i” parameter.
$ sqlcmd -S localhost -d AdventureWorks -U sa -P Pass@word1 -i
/home/labuser/scripts/basics/01_QueryHumanResourcesTable.sql

The T-SQL statements in the script file 01_QueryHumanResourcesTable.sql are below.


SELECT TOP 20 Name, GroupName FROM HumanResources.Department;

Execute a query with a join to look up the Product and Product Subcategory associated with ProductID
800.

Page 18
$ sqlcmd -S localhost -d AdventureWorks -U sa -P Pass@word1 -i
/home/labuser/scripts/basics/02_QueryProduct-ProductSubcategory.sql

The TSQL statements in the script file 02_QueryProduct-ProductSubcategory.sql are below.


SELECT
Product.ProductID
,Product.Name as Name
, Product.ProductNumber
, ProductSubcategory.Name as ProductSubcategory
FROM Production.Product
JOIN Production.ProductSubcategory
ON ProductSubcategory.ProductSubcategoryID = Product.ProductSubcategoryID
WHERE Product.ProductID = 800;

Execute a stored procedure


Execute the following query to run the uspgetBillOfMaterials stored procedure, which returns a recursive
list of components used to manufacture ProductID 800.
$ sqlcmd -S localhost -d AdventureWorks -U sa -P Pass@word1 -i
/home/labuser/scripts/basics/03_ExecuteStoredProcedure.sql

The TSQL statements in the script file 03_ExectueStoredProcedure.sql are below.


DECLARE @CheckDate DATETIME;
SET @CheckDate = GETDATE();
EXEC [AdventureWorks].[dbo].[uspGetBillOfMaterials] 800, @CheckDate;

Update a record
Update a row in the WorkOrder table to reflect that one quantity of ProductID 800 failed inspection and
had to be scrapped.
$ sqlcmd -S localhost -d AdventureWorks -U sa -P Pass@word1 -i
/home/labuser/scripts/basics/04_UpdateProductionWorkOrder.sql

The TSQL statements in the script file 04_UpdateProductionWorkOrder.sql are below.


Update Production.WorkOrder
SET ScrappedQty = 1
WHERE WorkOrderID = 70370;

Bulk Insert
The Bulk Insert feature allows you to import records into a table or view from a local data file.

To test this feature, you will need create a new file—SampleLocations.txt—in the directory

Page 19
/home/labuser/samples with the following content using the steps below.
1,Subassembly
2,Storage
3,Assembly
4,Final Assembly
5,Paint Shop
1. Create a new directory: /home/labuser/samples.
$ sudo mkdir -p -m a=rwx /home/labuser/samples
2. Move to the directory /home/labuser/samples.
$ cd /home/labuser/samples
3. Enter the nano editor to create the new file, SampleLocations.txt.
$ sudo nano SampleLocations.txt

4. Type or paste the following content into the file. (You will need to press the “i” key to
enter into “text insert” mode.)
1,Subassembly
2,Storage
3,Assembly
4,Final Assembly
5,Paint Shop
5. To save the file and exit the nano editor, use Ctrl-X to exit, and then confirm the
filename to save by selecting “Y.”

6. To avoid permissions issues, set full permissions on the file


$ sudo chmod 777 SampleLocations.txt

Note: Linux and Windows handle newlines differently, and SQL Server on Linux only recognizes newline
characters in the Windows format in this preview release. If you authored the SampleLocations.txt file in
Linux, use the dos2unix package and use it to create a version of the file that will be interpreted correctly
by SQL Server.

7. Use unix2dos utility to convert the Linux generated file to a SQL Server compatible
format.
$ unix2dos –n SampleLocations.txt WinSampleLocations.txt

Page 20
8. Create a new table in tempdb for Location data. Note the difference in the -d
parameter’s value; we’re now using tempdb.
$ sqlcmd -S localhost -d tempdb -U sa -P Pass@word1 -i
/home/labuser/scripts/basics/05_CreateTableInTempdb.sql

The TSQL statements in the script file 05_CreateTableInTempdb.sql are below.


USE [tempdb];

DROP TABLE IF EXISTS [tempdb].[dbo].[Locations]

CREATE TABLE Locations (


LocationID int,
Location varchar(255)
);
9. Use Bulk Insert to populate the Locations table with data from your text file.
$ sqlcmd -S localhost -d tempdb -U sa -P Pass@word1 -i
/home/labuser/scripts/basics/06_BulkInsertLocationsFromFile.sql

The TSQL statements in the script file 06_BulkInsertLocationsFromFile.sql are below.


USE [tempdb];

BULK INSERT Locations


FROM N'/home/labuser/samples/WinSampleLocations.txt'
WITH (FIELDTERMINATOR = ',');

Summary and conclusion


Bringing SQL Server to Linux is another way Microsoft is making its products and new innovations more
accessible to a broader set of users. Microsoft seeks to further enable every person and every
organization on the planet to achieve more. The announcement of SQL Server on Linux is a next step
toward making the industry-leading data management and business analytics platform available for any
data, to run any application, anywhere.

The private preview of SQL Server on Linux is available today, and Microsoft looks forward to working
with the community, customers, and partners to bring it to market. In this lab, you have run through the
steps to installing SQL Server on Linux, as well as the command-line tools using the distribution-specific
package manager. You have learned how to install updates to a Linux system and to manage the mssql-
server service using terminal commands.

Using mssql-tools sqlcmd, you restored a sample database from a file backup and performed a database
backup to file. Additionally, you have performed some basic database tasks, using .sql script files
containing T-SQL commands as input into sqlcmd.

Page 21
For a view into some of the performance and security features available with SQL Server for Linux, see the
second lab in this series, “Introduction to SQL Server on Linux for Linux Administrators.”

Page 22

Das könnte Ihnen auch gefallen