SQL Server on Linux
上QQ阅读APP看书,第一时间看更新

sqlcmd

The command-line utility, sqlcmd, offers batch execution of T-SQL scripts and a simple utility for executing T-SQL statements. It will be our primary interaction interface with SQL Server database engine. If you want to connect to your SQL Server instance you will need to type sqlcmd and the following parameters: (-S server name, -U user name -P password) in your bash command line.

You should avoid typing the password with parameter -P, because it will be visible on the screen. You can simply prevent this kind of situation in a matter skipping -P, and the database engine will ask your credentials after you press ENTER.

To connect on SQL Server, type the following command:

# sqlcmd -S sqlserver -U sa

In my case, the hostname is sqlserver; instead, you can type your IP address or localhost. After you press Enter, sqlcmd will ask you to provide a valid password for the sa account:

# Password:  

If login credentials are OK, you will get a screen output as follows:

Figure 3-3. Successful login on SQL Server instance

Now, let's type your first SQL statement to check version number of your SQL Server database engine. As you can see in Figure 3-3, sqlcmd is numbering code lines, starting from 1. So, each time you press Enter, you will jump to the next line 2, 3, and so on. But when you need to execute your command (Enter is not enough), you will need to finish your statement with batch directive GO. Take a look at the following listing:

1> SELECT @@VERSION
2> GO
---------------------------------------------------------
Microsoft SQL Server vNext (CTP1.3) - 14.0.304.138 (X64) 
        Feb 13 2017 16:49:12 
        Copyright (C) 2016 Microsoft Corporation. All rights reserved.
        on Linux (openSUSE Leap 42.2

(1 rows affected)  

First, we typed SELECT @@VERSION. After you press Enter, in the next line you need to type batch directive GO. Output (or result of execution) is an information message about SQL Server database engine and operating system version. Congratulations, you just finished your first SQL statement on a freshly installed SQL Server on Linux. It was not so hard. To exit in the bash command line, just type EXIT and press Enter. We will come back to sqlcmd in Chapter 4, Database in the Sandbox.