Рассмотрим инструмент командной строки, который используется для взаимодействия с Microsoft SQL Server
Постоянные читатели журнала, возможно, заметили, что я стал чаще писать о сценариях и некоторых развивающихся платформах и инструментах для взаимодействия с Microsoft SQL Server. Тому есть объяснение, но пока я не могу вдаваться в подробности. Достаточно сказать, что нас ждет дивный новый мир SQL Server на Linux, в котором взаимодействие с нашими экземплярами не ограничено средой Microsoft SQL Server Management Studio.
В этой статье речь пойдет об SQLCMD — инструменте командной строки, который используется для взаимодействия с Microsoft SQL Server.
Это не новый инструмент, он появился несколько десятков лет назад. Вы можете запускать SQLCMD не только из приложения командной строки Command, встроенного в Windows, но и из среды SQL Server Management Studio (SSMS).
Многие новые инструменты и методы взаимодействия с Microsoft SQL Server основаны на синтаксисе, используемом SQLCMD. Я взялся за эту ознакомительную статью, чтобы помочь вам разобраться в следующих вопросах:
- Запуск SQLCMD из командной строки.
- Основной синтаксис для подключения к Microsoft SQL Server с использованием SQLCMD.
- Основной синтаксис для передачи запросов в экземпляр Microsoft SQL Server с помощью SQLCMD.
- Выполнение запросов с использованием SQLCMD из среды SQL Server Management Studio.
Запуск SQLCMD из командной строки
Прежде чем подключиться к Microsoft SQL Server с помощью SQLCMD, необходимо запустить его. Конечно, сделать это очень просто, но, как вы знаете, мой подход заключается в том, чтобы провести вас по всем шагам от А до Я, не пропуская ни одного действия и не предполагая, что вам известны даже самые простые этапы процесса. Всегда досадно, когда не удается выполнить описанные в инструкции действия из-за отсутствия некоторых деталей. В своих статьях я стараюсь избежать таких упущений. В данном случае запустить SQLCMD настолько просто, что мне, вероятно, потребовалось в пять раз больше места, чтобы объяснить, почему я подробно разбираю столь элементарные вещи, чем на описание самого процесса.
Итак, нажмите комбинацию клавиш Windows + R, чтобы открыть окно выполнения, введите cmd, чтобы запустить приложение Command, а затем введите sqlcmd в ответ на приглашение и следом одну из многочисленных возможных комбинаций строк подключения, которые описаны ниже.
После успешного подключения вы получите приглашение вида «1>», чтобы начать взаимодействие с SQLCMD. При необходимости можно предоставить запрос как часть начального подключения для немедленной обработки, в соответствии с описанием, приведенным далее в статье.
Базовый синтаксис SQLCMD для установки подключения SQL Server
Как инструмент командной строки, SQLCMD представляет собой комбинацию команд и параметров. Ниже перечислены наиболее распространенные параметры, необходимые для организации подключения к экземпляру SQL Server, на котором выполняются инструкции.
Параметр сервера
- -S: указывает имя сервера или имя сервера/экземпляра в случае именованного экземпляра.
Параметры проверки подлинности
- -U: указывает имя пользователя при использовании проверки подлинности SQL Server;
- -P: пароль для пользователя, указанного в параметре -U;
- -E: обозначает использование доверенной проверки подлинности (Active Directory). Этот параметр выбран по умолчанию и не обязательно вводится при использовании доверенной проверки подлинности. Ниже приведены два примера инструкций подключения с помощью SQLCMD.
Сначала выполняется доверенная проверка подлинности для экземпляра по умолчанию с последующим именованным экземпляром:
sqlcmd -S <имя сервера> sqlcmd -S <имя сервера>\ <имя экземпляра>
При использовании доверенной проверки подлинности параметры -S остаются идентичными, достаточно просто указать имя пользователя и пароль:
sqlcmd -S <имя сервера > -U <имя пользователя > -P <пароль> sqlcmd -S <имя сервера>\ <имя экземпляра> -U <имя пользователя> -P <пароль>
При использовании проверки подлинности SQL Server можно опустить параметр -P в целях безопасности, и тогда во время выполнения будет запрошен пароль.
Параметры ввода
Существует два способа передать запрос в экземпляр SQL Server: как входной файл или нерегламентированный запрос.
- -Q или -q: текст запроса, передаваемого в экземпляр SQL Server;
- -i: предоставляет полный путь и имя файла, обрабатываемого экземпляром SQL Server.
Параметры вывода
- -o: предоставляет полный путь и имя файла для публикации результатов запроса.
В действительности список параметров гораздо больше. Чтобы получить дополнительные сведения, введите команду
sqlcmd -?
Две команды, на которые следует обратить внимание, управляют запуском скрипта и выходом из SQLCMD.
- GO: в отличие от знакомого вам аналога T-SQL, GO — не просто инструкция завершения пакета, а команда, выполняющая команду в SQLCMD.
- EXIT: эта команда завершает текущий сеанс SQLCMD. Впоследствии, чтобы установить активный сеанс, вам потребуется повторно ввести сведения о подключении.
Помните, что для всех перечисленных параметров используется синтаксис, обеспечивающий одновременный запуск SQLCMD и подключение к экземпляру SQL Server. Если вы уже запустили SQLCMD и получили приглашение «1>», то можно избавиться от инструкции sqlcmd в начале всех приведенных выше фрагментов программного кода.
Базовый синтаксис SQLCMD для выполнения запросов
Используя лишь эти несколько параметров, с помощью SQLCMD можно решать почти любые задачи. Рассмотрим три различных варианта применения описанных выше параметров.
Сценарий 1. Подключить экземпляр SQL Server по умолчанию с использованием проверки подлинности SQL и выполнить команду, которая составляет список имен всех баз данных в выходном файле:
sqlcmd -S <имя сервера> -U <имя пользователя> -P <пароль> -i "SELECT name FROM master;" -o c:\temp\db.txt
Сценарий 2. Подключить именованный экземпляр SQL Server с использованием доверенной проверки подлинности и выполнить последовательность команд из входного файла, отображая результаты команды в выходном файле:
sqlcmd -S <имя сервера>\ <имя экземпляра> -i C:\temp\sqlscript.sql -o c:\temp\db.txt
Сценарий 3. Подключить экземпляр SQL Server по умолчанию с использованием доверенной проверки подлинности и выполнить команду, которая выводит список имен всех баз данных непосредственно на экран:
sqlcmd -S <имя сервера > -i
«SELECT name FROM master;»
Использование SQLCMD из среды SQL Server Management Studio
Теперь, когда мы рассмотрели основные особенности подключения к SQLCMD и выполнения запросов из командной строки, обратим внимание на возможность выполнять форматированные скрипты SQLCMD из среды SQL Server Management Studio. Это превосходный способ продолжить использование уникальных функций сценариев, о которых я подробнее расскажу в следующей статье на тему SQLCMD, когда нужно запустить один скрипт, охватывающий несколько экземпляров последовательно.
Откройте новое окно запроса в среде SQL Server Management Studio. Необходимо поставить SSMS в известность, что этот запрос будет выполняться с помощью SQLCMD. Для этого перейдите к строке меню в верхней части экрана и выберите Query («Запрос»), а затем SQLCMD Mode («Режим SQLCMD»).
Выполним простое подключение к серверу. Сделать это можно с использованием доверенной проверки подлинности и простой команды:
: CONNECT <имя сервера>
Запрос немедленно отключается от экземпляра SQL после завершения выделенного вами текста запроса при его выполнении или полного содержимого запроса.
Нечто подобное приведенному ниже варианту демонстрирует возможность подключиться к экземпляру SQL Server (в данном случае используется локальный экземпляр SQL Server) и возвратить имя сервера и список всех баз данных на экземпляре:
: Connect. SELECT @@SERVERNAME, name FROM master.sys.databases ORDER BY name;
Конечно, это упрощенный подход с точки зрения запроса, но моя задача — рассмотреть различные варианты подготовки сценариев и использования SQLCMD. В следующей статье я расскажу об использовании SQLCMD в среде SSMS, что значительно облегчает работу со скриптами, требующими нескольких подключений для выполнения задачи.
Итак, теперь вы можете использовать SQLCMD из приложения Command операционной системы Windows или из среды SQL Server Management Studio. Кроме того, вы можете организовать подключение всего с несколькими необходимыми параметрами, знакомыми каждому, кто хотя бы немного работал с SQL Server, и передать запрос в SQL Server через SQLCMD для обработки.
Время прочтения: 4 мин.
В практике аудита использование СУБД SQL Server для хранения и анализа данных – одно из непременных условий, существенно повышающих качество проводимой работы.
А обслуживание базы данных, включающее, в том числе, резервное копирование данных, крайне важно для обеспечения ее бесперебойной работы.
В этой статье я поделюсь альтернативным способом того, как мы автоматизировали создание ежедневной резервной копии базы данных для обеспечения возможности восстановления данных в случае какого-либо инцидента. Мы сделали это с помощью служебной программы SQLCMD без запуска SQL Server Management Studio.
Но для начала немного простых примеров использования sqlcmd (все данные тестовые).
Посмотрим, как это работает в интерактивном режиме.
Запускаем командную строку Windows – cmd.
Чтобы подключиться к именованному экземпляру SQL Server, укажем имя сервера и имя экземпляра SQL Server (в примере соответственно DESKTOP\SQLEXPRESS), с которым необходимо соединиться.
sqlcmd -S DESKTOP\SQLEXPRESS –E
где:
–S указывает на server\instance_name;
–E –trusted connection (доверительное соединение).
Отображаемая в командной строке цифра 1> означает, что подключение состоялось и есть готовность принимать запросы для исполнения.
Если ранее при создании пользователя SQL Server для пользователя была включена аутентификацию SQL Server,
то при подключении требуется указать имя пользователя и ввести его пароль.
Чтобы это выполнить, предварительно необходимо выйти из sqlcmd и заново войти с указанием учетных данных:
sqlcmd -S DESKTOP\SQLEXPRESS –U DB_User
Командная строка запросит пароль для пользователя DB_User, который необходимо ввести с клавиатуры.
При желании можно указать пароль в командной строке, хотя это не рекомендуется по соображениям безопасности:
sqlcmd -S DESKTOP\SQLEXPRESS –U DB_User –P 12345678
Давайте теперь проверим текущую базу данных.
При создании входа в SQL Server можно определить базу данных, в которую необходимо войти, по умолчанию. Если она не указана, то базой данных по умолчанию будет является основная база данных (master).
select db_name()
go
Следующий пример использования sqlcmd – вывод списка баз данных в экземпляре SQL:
select name from sys.databases
go
Теперь давайте посмотрим на запуск sqlcmd в командном режиме.
Получим список таблиц в базе данных db1, выведя его в файл tables.txt, используя в sqlcmd подготовленный заранее и сохраненный на жестком диске ПК, сценарий tablesList.sql со следующим содержанием:
select table_name from db1.information_schema.tables;
Затем вызовем sqlcmd для выполнения созданного сценария tablesList.sql:
sqlcmd -S DESKTOP\SQLEXPRESS -E -iC:\Users\User\SQL\Scripts\tablesList.sql -oC:\Users\User\SQL\tables.txt
где:
—i используется для указания ввода, указывается файл сценария, в примере это сохраненный tablesList.sql;
—o используется для отображения результатов вывода в файл, в примере это tables.txt
В tables.txt отображается следующий результат (для примера выбрана тестовая база данных, состоящая из одной таблицы):
Теперь вернемся к нашей задаче автоматизации резервного копирования с использованием sqlcmd и планировщика задач Windows.
Во-первых, создадим файл сценария резервного копирования базы данных db1 и сохраним его в файле backup.sql:
declare @Backup nvarchar(400)
set @Backup=concat('C:\Users\User\SQL\Backup\db1-',(format(getdate(),'yyyy-MM-dd-hh-mm-ss-tt')),'.bak')
backup database [db1] to disk=@Backup
with noformat, noinit, name = n'db1-Backup', skip, norewind, nounload, stats=10
go
Файл резервной копии в результате выполнения этого сценария сохраняется в каталог C:\Users\User\SQL\Backup\.
Далее создаем командный файл run-sqlcmd-backup.bat следующего содержания:
@Echo off
sqlcmd -S DESKTOP\SQLEXPRESS -E -iC:\Users\User\SQL\Scripts\backup.sql
И, наконец, открываем Планировщик заданий Windows (подробнее о планировщике заданий Windows можно прочесть в официальных документах Microsoft по этой тематике), для того, чтобы создать задачу резервного копирования базы данных db1, запускающую командный файл run-sqlcmd-backup.bat по необходимому расписанию.
В итоге с помощью sqlcmd мы получили регулярное резервное копирование выбранной нами базы данных.
The sqlcmd utility in SQL Server is a command-line tool that lets you submit T-SQL statements or batches to local and remote instances of SQL Server. The utility is extremely useful for repetitive database tasks such as batch processing or unit testing. It also provides an easy way of simulating load to a database under development.
To help you develop and test sqlcmd scripts, the query window in SQL Server Management Studio (SSMS) supports SQLCMD Mode, which lets you run most sqlcmd ‘colon’ directives as well as T-SQL statements. You can submit commands from within Windows script files (such as .bat), via sp_cmdshell, or through SQL Server Agent CmdExec jobs. You can also run sqlcmd within PowerShell. In addition, PowerShell includes, via SQLPS, a version of sqlcmd called invoke-sqlcmd
that runs many, but not all, of the directives. This has the advantage of returning results as PowerShell objects.
In this article, I introduce you to the basics of the sqlcmd utility and discuss how to create scripts from within SSMS and at a Windows command prompt and how to run or schedule these scripts. Once you know how to use the utility within these environments, you’ll be able to create commands that you can add to your Windows script files, SQL Server Agent jobs, and PowerShell SQLPS applications.
The article includes a number of examples that demonstrate how to use sqlcmd. I developed these examples against a local instance of SQL Server 2012, with the AdventureWorks2012 database installed. However, you can use sqlcmd with any accessible SQL Server instance, from version 2005 on, and against any accessible database. Simply substitute the connection and database information in the examples, as appropriate, and you should have no problem following along.
NOTE: The sqlcmd utility replaces the osql utility in earlier versions of SQL Server. Although the utility is still supported in SQL Server 2012, Microsoft plans to remove osql in a future version of SQL Server and recommends that you avoid using it for current development.
Running sqlcmd in SQL Server Management Studio
If you’re already using SSMS regularly, as are most SQL Server developers and DBAs, you’ll find the SSMS query window a good place to start learning about sqlcmd. To run sqlcmd statements, you must change the query window to SQLCMD Mode by clicking the SQLCMD
Mode option on the Query menu.
NOTE: You can also click the SQLCMD Mode button on the toolbar if the button is there. If it’s not, you’ll have to manually add it by customizing your toolbar. The exact method for doing so varies from one SQL Server version to the next, so refer to SQL Server Books Online for details specific to your version.
SSMS in SQLCMD Mode provides a handy environment for creating and testing your sqlcmd statements. Editing commands, for example, is much easier in SSMS than at a Windows command prompt. To get started in SSMS, connect to a SQL Server instance, open a query window, and switch to SQLCMD Mode. Then start typing.
When working in SQLCMD Mode, you can enter two types of statements: sqlcmd directives and T-SQL statements. The sqlcmd directives are a set of special commands you can use in conjunction with the T-SQL statements. Let’s look at an example to better understand how they work. The following set of statements delete the PersonData.txt file if it exists, connects to a local instance of SQL Server, retrieves data from the Person table in the AdventureWorks2012 database, and saves the output to a new copy of the PersonData.txt file:
:!!if exist C:\DataFiles\PersonData.txt del C:\DataFiles\PersonData.txt :connect localhost\sqlsrv2012 :out C:\DataFiles\PersonData.txt USE AdventureWorks2012; SELECT FirstName, LastName FROM Person.Person WHERE PersonType = ’em’ AND LastName = ‘smith’; |
We’ll go through this code line-by-line shortly, but first take a look at Figure 1. Notice that the sqlcmd directives are automatically highlighted in gray when you work in SQLCMD Mode. The T-SQL statements appear as they would in regular query mode.
Figure 1: Running command in SQLCMD Mode in SSMS
As you can see in Figure 1, a colon (:
) precedes the sqlcmd directives. The colon is required for most of these commands. For a few of them, however, such as quit
and exit
, you can omit the colon. (This was done to support backward compatibility with the osql utility.) For details about this and other command-related issues, see the topic “sqlcmd Utility” in SQL Server Books Online. In the meantime, let’s look at the commands used in our example. The first one begins with double exclamation points (!!
):
:!!if exist C:\DataFiles\PersonData.txt del C:\DataFiles\PersonData.txt |
The exclamation points let you run a Windows operating system command, such as those you’d run directly at a command prompt. In this case, the command first uses if
exists
to verify the existence of the PersonData.txt file and then uses del
to remove the file if it exists. (Note that each sqlcmd directive must run on its own line.)
The second line in our example uses the co
nnec
t
command to specify a connection to a SQL Server instance:
:connect localhost\sqlsrv2012 |
Although this example is specific to a local SQL Server instance, you can connect to any available instance for which you’ve been granted access. If that instance is the default one, you need only provide the server name. In addition, when you specify the server and, optionally, the instance name, sqlcmd uses Windows authentication to connect to SQL Server with your current account. However, you can also specify a username and password when connecting to an instance. To specify a username, add the -U
switch followed by the username. To include a password, add the -P
switch followed by the password. If you enter the username option without the password option, you’ll be prompted for a password.
The next sqlcmd directive in our example is out
:
:out C:\DataFiles\PersonData.txt |
The command specifies that all query results should be redirected to an output file, in this case, the PersonData.txt file. If the file already exists when you run this commend, the file will be truncated. For this reason, you might not need to run a Windows command to first delete the file, as we do in the first line. It all depends on your specific needs.
Next in our example are the T-SQL statements that change the database context to AdventureWorks2012
and retrieve data from the Person
table:
USE AdventureWorks2012; SELECT FirstName, LastName FROM Person.Person WHERE PersonType = ’em’ AND LastName = ‘smith’; |
The two statements are both straightforward T-SQL. You simply include them along with your sqlcmd directives. When you run a block of code such as the one in our example, your commands and T-SQL statements are executed in the specified order. For this reason, after the connect
command runs, you’ll see the following results in the output pane of the query window:
Connecting to localhost\sqlsrv2012... |
However, after the out
command runs, query output is saved to the PersonData.txt file. The following results show what you’ll find in the file:
FirstName LastName —————- ————- Denise Smith Samantha Smith (2 row(s) affected) Disconnecting connection from localhost\sqlsrv2012... |
Of course, you don’t have to redirect your output to a file, but if you don’t, the results will appear in the output pane of the query window.
Running sqlcmd in Interactive Mode
As mentioned earlier, using SQLCMD Mode in SSMS can be useful for developing and testing your sqlcmd code. However, you can then run your commands at a Windows command prompt by using sqlcmd in interactive mode. To work in interactive mode, open a command prompt window and enter sqlcmd
at the command prompt. The prompt’s drive letter will be replaced by a 1
, which represents the first line where you start entering your commands. The lines are numbered sequentially until all the commands are submitted, and then the numbering starts again.
When you use sqlcmd
to switch to interactive mode, the utility establishes a connection to the default instance of SQL Server. If your system includes only named instances or you want to connect to a specific instance, you must specify the instance by adding the –S
switch and instance name, as shown in the following command:
In this case, I’ve used a period to represent the local computer, and I’m connecting to an instance named SqlSrv2012. But you can connect to any accessible instance.
Once you’ve entered interactive mode, you can type in your T-SQL statements. To add a line break after a statement or part of a statement, press Enter. The sqlcmd utility does not submit your T-SQL statements to SQL Server until you run the GO
command. For example, suppose you enter the following statements at the sqlcmd command prompt:
USE AdventureWorks2012; SELECT FirstName, LastName FROM Person.Person WHERE PersonType = ’em’ AND LastName = ‘smith’; GO |
The USE
statement will change the database context to the AdventureWorks2012 database, and the SELECT
statement will retrieve data from the database. However, these statements are not submitted to SQL Server until you type GO
and then press Enter. The utility then submits the statements and returns the results to the command prompt window.
NOTE: The GO
command is a client-side ‘batch delimiter’ directive that is common to sqlcmd and SSMS. It is not a Transact SQL statement. it can be followed on the same line by the number of times you wish to run the preceding batch. Unless you specify this, it is just run once.
Figure 2 shows what the command prompt window looked like on my system after I switched to interactive mode and submitted the statements. Notice that with each line of code, the line numbers are incremented, but after the GO
command runs, the command prompt returns to 1
.
Figure 2: Running a sqlcmd query in interactive mode
In the examples we’ve looked at so far, our T-SQL has consisted primarily of data manipulation language (DML) statements. However, you’re not limited to DML when issuing T-SQL statements. You can run data definition language (DDL) statements, execute stored procedures and perform database maintenance. For example, you can just as easily run the following SELECT...INTO
statement:
USE AdventureWorks2012; SELECT FirstName, LastName INTO dbo.Employees FROM Person.Person WHERE PersonType = ’em’; GO |
Once again, you enter each line and then submit the statements by using GO
. Figure 3 shows what the command prompt window looked like on my system after adding the next set of commands.
Figure 3: Using sqlcmd in interactive mode to create a table
In this case, I typed nothing at the first line and simply pressed Enter to add space to my commands. Then I typed the T-SQL statements and entered GO
. The results show that I changed the database context and that 273 rows were affected. If I had wanted, I could have then run a query against the new table to verify that it had been created correctly.
When using sqlcmd in interactive mode, you can also include sqlcmd directives, as we did in SSMS in SQLCMD Mode. For example, the following set of statements includes several sqlcmd directives:
:connect localhost\sqlsrv2012 :out C:\DataFiles\PersonData.txt USE AdventureWorks2012; SELECT FirstName, LastName FROM Person.Person WHERE PersonType = ’em’ AND LastName = ‘smith’; GO :exit |
The connect
command establishes a connection to a SQL Server instance, and the out
command specifies that any query results should be outputted to the PersonData.txt file. Next come the T-SQL statements, followed by the GO
command. After all this, we issue an exit
command, which tells sqlcmd to quit interactive mode and return the command prompt window to its normal state.
Running sqlcmd in Command Mode
Interactive mode is useful when you want to run ad hoc queries at a command prompt. However, where you’re likely to gain the most benefit from the sqlcmd utility is by creating complete commands that you can run at a command prompt (in what I refer to as command mode), add to your Windows script files, run as part of SQL Server Agent jobs, or use in other ways.
The best way to learn how to create these types of commands is to return once again to the command prompt window. However, rather than switch to interactive mode, we can simply run our commands at the default prompt. For example, the following command retrieves data from the AdventureWorks2012 database on a local named instance of SQL Server:
sqlcmd —S localhost\sqlsrv2012 —d AdventureWorks2012 —Q «SELECT FirstName, LastName FROM Person.Person WHERE BusinessEntityID = 240« |
The first issue worth pointing out is that the command, as shown here, might appear on multiple lines when you view it. In reality, this is a single-line command that is wrapping across multiple lines here because of margin limitations. However, you do not press Enter until you’ve entered the entire command.
The command itself starts with sqlcmd
to launch the utility and then uses the -S
switch to specify the SQL Server instance, as we sometimes do when entering interactive mode. Next, we use the -d
switch to specify the database. (Note that switch names are case-sensitive.) Finally, we use the -Q
switch to define our T-SQL statement, enclosed in double quotes. In this case, we use an uppercase Q to run the statement and immediately exit the sqlcmd environment. If we use a lowercase q, we’d end up in interactive mode. Figure 4 shows what the command prompt window looks like after I ran the command.
Figure 4: Running sqlcmd in command mode in the Windows console
Rather than returning the results to the command window, we can instead use the -o
switch to output the data to a text file, as shown in the following example:
sqlcmd —S localhost\sqlsrv2012 —d AdventureWorks2012 —Q «SELECT FirstName, LastName FROM Person.Person WHERE PersonType = ’em’ ORDER BY LastName, FirstName« —o C:\DataFiles\Employees.txt |
This time, we’re returning a list of employees from the Person table and ordering the data by name. When we run the command, the sqlcmd utility adds the employee names to the file, without returning results to the command prompt.
The sqlcmd utility also lets us run script files that contain the statements we want to execute. For example, suppose we create a script file that contains the following SELECT
statement:
SELECT FirstName, LastName FROM Person.Person WHERE PersonType = ’em’ ORDER BY LastName, FirstName |
In this case, I’ve named the file EmployeeQuery.sql and saved it to the C:\DataFiles folder. To run the statement, I create a command that uses the -i
switch to call the EmployeeQuery.sql file, as shown in the following example:
sqlcmd —S localhost\sqlsrv2012 —d AdventureWorks2012 —i C:\DataFiles\EmployeeQuery.sql —o C:\DataFiles\Employees.txt |
Once again, the results are outputted to the Employees.txt file.
At times, you might want to create a script file that you can use in multiple situations, in which case you might want to be able to pass in variable values when calling the file. To do so, you add placeholders to your script file that let you pass in the values.
For example, suppose you want to be able to specify the person type and last name when querying the Person table. You can create a script file that contains a T-SQL statement similar to the following:
SELECT FirstName, LastName FROM Person.Person WHERE PersonType = ‘$(type)’ AND LastName = ‘$(name)’ |
Notice that, to specify the PersonType value in the WHERE
clause, I use $(type)
. The type
value serves as the variable name, which can be referenced when calling the file. To use it as a variable, I’ve enclosed it in parentheses, preceded those with a dollar sign, and enclosed the entire thing in single quotes. I then follow the same convention for the name
variable.
I saved the file as EmployeeQuery2.sql. Now, when I call the file within my command, I also include the -v
switch and specify values for the type
and name
variables, as shown in the following example:
sqlcmd —S localhost\sqlsrv2012 —d AdventureWorks2012 —i C:\DataFiles\EmployeeQuery2.sql —v type=«em« id=«smith«» —o C:\DataFiles\Employees2.txt |
Notice that I use a single -v
argument and specify a value enclosed in double quotes for each variable. Once again, the command returns data about two employees whose last name is Smith. The query results are outputted to the Employees2.txt file.
Working with the sqlcmd Utility
Not surprisingly, the sqlcmd utility can do a lot more than what I’ve demonstrated here. As mentioned earlier, the utility supports a number of sqlcmd directives in addition to those we’ve covered. The utility also supports many more switches than what we’ve used in the examples. Again, refer to the topic “sqlcmd Utility” in SQL Server Books Online for more details about commands and switches. You’ll also find plenty of useful information in the Simple-Talk workbench “The SQLCMD workbench,” written by Robyn Page and Phil Factor. What you’re likely to find is that the more you dig into the sqlcmd utility, the better you’ll appreciate what a valuable tool it can be, especially if you want to automate and schedule tasks related to local and remote instances of SQL Server.
Certainly! Here’s a concise explanation along with a code snippet for your post on «cmd sql server»:
The Command Prompt (cmd) can be used to interact with SQL Server by executing queries through the SQLCMD utility.
sqlcmd -S server_name -U username -P password -d database_name -Q "SELECT * FROM table_name"
Understanding CMD and SQL Server
What is CMD?
Command Prompt, commonly known as CMD, is a command-line interpreter in Windows operating systems. It provides an interface for users to execute commands, run scripts, and manage system operations efficiently. Its significance in database management cannot be overstated, as it allows direct access to database capabilities without needing a graphical user interface (GUI). This is especially useful for developers and systems administrators who require speed and precision in their database interactions.
What is SQL Server?
SQL Server is a powerful relational database management system (RDBMS) developed by Microsoft. It is used to store and retrieve data as requested by other software applications. SQL Server is lauded for its robust features, which include data security, transaction management, and support for complex queries and analytics. This makes it a popular choice for businesses that handle large volumes of data.
Ping SQL Server from Cmd: A Quick Guide to Connectivity
Getting Started with SQL Server in CMD
Installing SQL Server Command Line Tools
Before you can use CMD with SQL Server, you need to install the necessary command line tools. Depending on your operating system, the installation steps may vary. If you are using Linux, for example, ensure that you have the prerequisites in place first:
To install SQL Server tools, you can use the following command:
sudo apt-get install mssql-tools
After installation, ensure the tools are properly installed by typing `sqlcmd -?` in the Command Prompt to view the available commands and options.
Connecting to SQL Server Using CMD
Once the SQL Server command line tools are installed, you can establish a connection to your SQL Server instance. The typical command structure to connect to a SQL Server instance is as follows:
sqlcmd -S <ServerName> -U <Username> -P <Password>
- Replace `<ServerName>` with the name of your SQL Server instance.
- `<Username>` represents your SQL Server username.
- `<Password>` is the corresponding password.
If your server is set to use Windows Authentication, you can omit the username and password and instead use the following command:
sqlcmd -S <ServerName> -E
This allows you to log in using your Windows credentials.
Cmd Open Server Manager: Quick Steps to Get Started
Basic SQL Commands via CMD
Selecting Data from a Table
The `SELECT` command is fundamental in retrieving data stored in a database. A basic syntax looks like this:
SELECT * FROM Customers;
This command retrieves all rows from the «Customers» table. However, best practice dictates that you should specify the columns you need to enhance performance and clarity.
Inserting Data into a Table
To insert new records into a table, you will use the `INSERT` command. Here’s how you can add a new customer:
INSERT INTO Customers (CustomerName, ContactName) VALUES ('Cardinal', 'Tom B. Erich');
This command adds a new row to the «Customers» table, specifying both the customer’s name and contact name.
Updating Data in a Table
To modify existing records, you’re going to need the `UPDATE` command. For example, if you want to change the contact name of a specific customer, you will use:
UPDATE Customers SET ContactName = 'Ana Trujillo' WHERE CustomerID = 1;
This command updates the contact name for the customer with an ID of 1.
Deleting Data from a Table
If you need to remove records from a table, use the `DELETE` command carefully. For instance:
DELETE FROM Customers WHERE CustomerID = 1;
This will eliminate the customer with CustomerID 1 from the «Customers» table.
Cmd Kill Service: A Simple Guide to Command Mastery
Advanced Commands and Features
Creating a Database
To create a new database, use the `CREATE DATABASE` command. Here’s an example:
CREATE DATABASE SampleDB;
Executing this command will establish a new database called «SampleDB.»
Creating Tables and Defining Schema
Defining a structure for your data is crucial. You can create tables by specifying their schema using the `CREATE TABLE` command:
CREATE TABLE Customers (
CustomerID int,
CustomerName varchar(255),
ContactName varchar(255)
);
This command sets up a «Customers» table containing three columns: CustomerID, CustomerName, and ContactName.
Joining Tables
In relational databases, it’s often necessary to combine data from multiple tables. SQL supports several types of JOIN operations. A simple INNER JOIN command looks like this:
SELECT Orders.OrderID, Customers.CustomerName
FROM Orders
INNER JOIN Customers ON Orders.CustomerID = Customers.CustomerID;
This example retrieves order IDs along with the corresponding customer names by linking the «Orders» and «Customers» tables.
Cmd Generator: Create Commands Effortlessly in Cmd
Managing Databases via CMD
Listing All Databases
To view all databases within your SQL Server instance, execute the following command:
SELECT name FROM sys.databases;
This command returns a list of all databases available on your server.
Backing Up and Restoring Databases
Database backup and restoration are key for data integrity. You can back up a database using the following command:
BACKUP DATABASE SampleDB TO DISK = 'C:\Backup\SampleDB.bak';
This command creates a backup of «SampleDB.» To restore it, use:
RESTORE DATABASE SampleDB FROM DISK = 'C:\Backup\SampleDB.bak';
Executing this command will restore «SampleDB» from the specified backup file.
Cmd Systeminfo: Your Quick Guide to System Details
Error Handling and Troubleshooting
Common CMD and SQL Server Errors
While using CMD with SQL Server, you may encounter a variety of issues, including:
- Connection issues, often due to improper credentials or server not reachable.
- Syntax errors, which occur when SQL commands are incorrectly written.
Resolving Errors
When dealing with errors, it is essential to read error messages carefully. For connection problems, double-check your server name, username, and password. Be sure to ensure that SQL Server is running and that any required firewall rules allow traffic.
Mastering Cmd Winver: Quick Guide to Check Windows Version
Best Practices for Using CMD with SQL Server
Writing Efficient SQL Commands
To optimize the performance of your SQL queries, consider specifying only the columns you need instead of using `SELECT *`. This minimizes the amount of data processed and improves response times.
Maintaining Security
Data security is paramount. Always use parameterized queries to prevent SQL injection, and manage user permissions diligently to restrict access to sensitive data.
Mastering Cmd Sqlplus: A Quick User’s Guide
Conclusion
In summary, leveraging CMD SQL Server capabilities allows for powerful and efficient database management. From connecting to instances and executing basic commands to utilizing advanced features, mastering command line usage can significantly enhance your database skills. As you continue to practice and explore, remember to stay updated with best practices to ensure you maintain robust database integrity and performance.
Practical guide on how to use the SQL Server SQLCMD tool.
The tutorial about the SQLCMD examples is divided into different sections, providing a wide overview of various functionalities, use cases, and handy tips with the command line tool. It includes practical code examples to enhance understanding and automate daily DBA tasks.
SQLCMD is a command-line tool that allows you to interact with SQL Server efficiently. With the SQL Server SQLCMD tool, you can run Transact-SQL commands, system procedures, and SQL scripts. This invaluable tool provides a bridge between the user and SQL Server, allowing for direct communication and manipulation of databases.
1.1 Why use the SQL Server SQLCMD command line tool?
SQLCMD is not just a tool but a powerful asset in the hands of database administrators and developers. Through its streamlined interface, it brings the following advantages:
- Ease of Access: SQLCMD makes it simple to run and manage SQL queries directly from the command line.
- Automation Capability: You can script complex procedures, enabling a smooth workflow and reducing the room for error.
- Integration with Other Tools: It seamlessly integrates with various other SQL Server tools, enhancing functionality and efficiency.
1.2 How SQLCMD Works ?
The MS SQL command-line utility works as an interface to SQL Server. By accepting commands in Transact-SQL (T-SQL), it translates human-readable queries into actions that the SQL Server can perform. This includes executing commands, retrieving data, and even managing entire databases. The convenience, flexibility, and power of the SQLCMD tool make it an essential resource for anyone working with Microsoft SQL.
2. Installation and Configuration of SQLCMD
To embark on the journey of using SQLCMD, a couple of initial steps need to be undertaken. First and foremost, the installation of SQLCMD must be accomplished on your operating system. It’s a fairly straightforward process that can be executed by following the specific instructions provided for your OS version: Windows or Linux.
2.1 Difference between the Windows and the Linux configurations
The installation and configuration of SQLCMD vary between Windows and Linux. On Windows, SQLCMD can be installed as a part of the SQL Server Management Studio (SSMS) and is typically configured using a GUI interface. Commands can be run from the Command Prompt.
In contrast, Linux requires manual installation of the mssql-tools
package and uses a terminal interface for configuration.
The command-line syntax may differ slightly between the two, such as the path conventions and scripting nuances. Despite these differences, both provide a powerful command-line tool for managing SQL Server instances.
2.2 Installing SQLCMD on Windows or Linux
The commands are the same for both Windows and Linux, as SQL Server’s command-line tools are designed to work consistently across different platforms.
# Windows sqlcmd -S localhost -U sa -P password # Linux sqlcmd -S localhost -U sa -P password
3. SQLCMD examples with basic commands
Let’s dive into some basic commands to get familiar with the SQL Server SQLCMD tool.
3.1 Connecting to a Database
To connect to a specific database, use the following command:
sqlcmd -S server_name -d database_name -U username -P password
3.2 SQL CMD examples with queries
With SQLCMD, you can easily run SQL queries directly from the command line. Here’s an example:
sqlcmd -Q "SELECT * FROM Users"
4. SQL Server SQLCMD Advanced Use Cases
SQLCMD is not just limited to basic queries. It provides several advanced functionalities.
4.1 Using Variables with SQL Server SQLCMD
You can use variables within your SQL scripts. Here’s an example:
sqlcmd -v var_name="value" -Q "SELECT * FROM Table WHERE Column = @var_name"
SQLCMD provides a robust interface to interact with SQL Server, allowing for various advanced use cases. Below are some of them.
4.2 SQL CMD example to Query Multiple Databases
You can use SQLCMD to execute queries across multiple databases on the same server.
sqlcmd -S localhost -U sa -P password -d Database1 -Q "SELECT * FROM Table1; USE Database2; SELECT * FROM Table2;"
4.3 Running Scripts from Files
You can run a SQL script from a file using the -i
option.
sqlcmd -S localhost -U sa -P password -i MyScript.sql
4.4 Outputting Query Results to a File
Redirect the output of your queries to a text file using the -o
option.
sqlcmd -S localhost -U sa -P password -Q "SELECT * FROM MyTable;" -o output.txt
4.5 Connecting to a Named Instance
If you’re working with a named instance of SQL Server, specify it using the -S
option.
sqlcmd -S localhost\InstanceName -U sa -P password
4.6 Utilizing Windows Authentication
You can connect to SQL Server using Windows Authentication by omitting the username and password.
sqlcmd -S localhost -E
4.7 Executing Commands with Variables
SQLCMD allows the use of variables within your scripts. You can declare and use them with the :SETVAR
command.
sqlcmd -S localhost -U sa -P password -Q "EXEC sp_databases; :SETVAR MyVariable 'MyValue'; PRINT '$(MyVariable)';"
4.8 Implementing Transaction Control
You can manage transactions within your SQLCMD sessions by using the standard T-SQL transaction control statements like BEGIN TRANSACTION
, COMMIT
, and ROLLBACK
.
sqlcmd -S localhost -U sa -P password -Q "BEGIN TRANSACTION; UPDATE Table1 SET Column1 = 'value' WHERE Column2 = 'condition'; COMMIT;"
4.9 Generate XML Output using the SQLCMD tool
You can generate XML output from a query by using the -y
or -Y
options with the -r
option.
sqlcmd -S localhost -U sa -P password -Q "SELECT * FROM MyTable FOR XML AUTO;" -r 1 -o output.xml
5. SQLCMD Tips and Best Practices
To make the most of SQLCMD, follow these best practices:
- Always close connections when not in use.
- Use the
-b
switch to halt execution on errors. - Optimize scripts by using parameters.
Conclusion on SQLCMD examples
The SQLCMD examples offers an array of possibilities to manage SQL Server from the Windows command line. Explore different use cases, and don’t hesitate to delve into more complex operations.
https://expert-only.com/en/ms-dos/copy-windows-files-with-cmd/