Руководство по подключение к экземпляру sql server и выполнение запросов с помощью sql server management studio (ssms)tutorial: connect to and query a sql server instance by using sql server management studio (ssms)

Компоненты среды SQL Server Management StudioSQL Server Management Studio components

В этом разделе описываются различные компоненты окна, доступные в рабочей области, и их использование.This section describes the various window components that are available in the workspace, and how to use them.

  • Чтобы закрыть окно, щелкните X в правом углу заголовка окна.To close a window, select the X in the right corner of the title bar.

  • Чтобы снова открыть окно, выберите это окно в меню Вид.To reopen a window, select the window in the View menu.

  • Обозреватель объектов (F8): представление в виде дерева, в котором отображаются все объекты базы данных на сервере.Object Explorer (F8): Object Explorer is a tree view of all the database objects in a server. В этом представлении отображаются базы данных ядра СУБД SQL Server, SQL Server Analysis Services, SQL Server Reporting Services и SQL Server Integration Services.This view includes the databases of the SQL Server Database Engine, SQL Server Analysis Services, SQL Server Reporting Services, and SQL Server Integration Services. Обозреватель объектов содержит сведения обо всех серверах, которые подключены к нему.Object Explorer includes information for all servers that are connected to it.

  • Окно запросов (CTRL+N): выберите Новый запрос и введите запрос Transact-SQL (T-SQL) в этом окне.Query Window (Ctrl+N): After you select New Query, enter your Transact-SQL (T-SQL) queries in this window. Результаты запросов также отображаются в этом окне.The results of your queries also appear here.

  • Свойства (F4): представление «Свойства» будет отображаться, когда открыто окно запросов.Properties (F4): You can see the Properties view when the Query Window is open. В представлении отображаются основные свойства запроса.The view displays basic properties of the query. Например, в нем отображаются время запуска запроса, количество возвращенных строк и сведения о подключении.For example, it shows the time that a query started, the number of rows returned, and connection details.

  • Обозреватель шаблонов (CTRL+ALT+T): обозреватель шаблонов содержит различные готовые шаблоны T-SQL.Template Browser (Ctrl+Alt+T): Template Browser has various pre-built T-SQL templates. Эти шаблоны можно использовать для выполнения различных действий, таких как создание или резервное копирование баз данных.You can use these templates to perform various functions, such as creating or backing up a database.

  • Подробные сведения обозревателя объектов (F7): это представление является более детализированными по сравнению с обозревателем объектов.Object Explorer Details (F7): This view is more granular than the view in Object Explorer. Представление «Подробные сведения обозревателя объектов» можно использовать для одновременного управления несколькими объектами.You can use Object Explorer Details to manipulate multiple objects at the same time. Например, в этом окне можно выбрать несколько баз данных и одновременно удалить их или создать сценарии для них.For example, in this window, you can select multiple databases, and then either delete them or script them out simultaneously.

Комментирование и раскомментирование кода T-SQLComment/uncomment your T-SQL code

Части текста можно закомментировать и раскомментировать с помощью кнопки Закомментировать на панели инструментов.You can comment and uncomment portions of your text by using the Comment button on the toolbar. Закомментированный текст не выполняется.Text that is commented out is not executed.

  1. Откройте среду SQL Server Management Studio.Open SQL Server Management Studio.

  2. Подключитесь к серверу SQL Server.Connect to your SQL server.

  3. Откройте окно «Новый запрос».Open a New Query window.

  4. Вставьте следующий код T-SQL в текстовое окно.Paste the following T-SQL code in your text window.

  5. Выделите часть текста с инструкцией Alter Database и нажмите кнопку Закомментировать на панели инструментов:Highlight the Alter Database portion of the text, and then select the Comment button on the toolbar:

  6. Нажмите кнопку Выполнить, чтобы выполнить раскомментированную часть текста.Select Execute to run the uncommented portion of the text.

  7. Выделите все, за исключением инструкции Alter Database, а затем нажмите кнопку Закомментировать:Highlight everything except for the Alter Database command, and then select the Comment button:

    Примечание

    Текст можно комментировать с помощью сочетания клавиш CTRL+K, CTRL+C.The keyboard shortcut to comment text is CTRL + K, CTRL + C.

  8. Выделите часть текста с инструкцией Alter Database и нажмите кнопку Раскомментировать на панели инструментов:Highlight the Alter Database portion of the text, and then select the Uncomment button to uncomment it:

    Примечание

    Чтобы раскомментировать текст, используйте сочетания клавиш CTRL+K, CTRL+U.The keyboard shortcut to uncomment text is CTRL + K, CTRL + U.

  9. Нажмите кнопку Выполнить, чтобы выполнить раскомментированную часть текста.Select Execute to run the uncommented portion of the text.

解除安裝Uninstall

在您將 SSMS 解除安裝之後,某些共用元件仍會維持安裝。There are shared components that remain installed after you uninstall SSMS.

維持安裝的共用元件為:The shared components that remain installed are:

  • Microsoft .NET Framework 4.7.2Microsoft .NET Framework 4.7.2
  • Microsoft OLE DB Driver for SQL ServerMicrosoft OLE DB Driver for SQL Server
  • Microsoft ODBC Driver 17 for SQL ServerMicrosoft ODBC Driver 17 for SQL Server
  • Microsoft Visual C++ 2013 可轉散發套件 (x86)Microsoft Visual C++ 2013 Redistributable (x86)
  • Microsoft Visual C++ 2017 可轉散發套件 (x86)Microsoft Visual C++ 2017 Redistributable (x86)
  • Microsoft Visual C++ 2017 可轉散發套件 (x64)Microsoft Visual C++ 2017 Redistributable (x64)
  • Microsoft Visual Studio Tools for Applications 2017Microsoft Visual Studio Tools for Applications 2017

這些元件可以與其他產品共用,因此不會解除安裝。These components aren’t uninstalled because they can be shared with other products. 若解除安裝,可能會導致其他產品無法使用。If uninstalled, you may run the risk of disabling other products.

自動安裝Unattended install

您也可以使用命令提示字元指令安裝 SSMS。You can also install SSMS using a command prompt script.

苦要在不提供 GUI 提示的背景中安裝 SSMS,請執行下列步驟。If you want to install SSMS in the background with no GUI prompts, then follow the steps below.

  1. 啟動權限較高的命令提示字元。Launch the command prompt with elevated permissions.

  2. 在下列命令提示字元中鍵入命令。Type the command below in the command prompt.

    範例:Example:

    您也可以傳遞 /Passive (而不是 /Quiet ),以查看安裝程式 UI。You can also pass /Passive instead of /Quiet to see the setup UI.

  3. 若一切順利,就會像範例般顯示安裝在 %systemdrive%\SSMSto\Common7\IDE\Ssms.exe 的 SSMS。If all goes well, you can see SSMS installed at %systemdrive%\SSMSto\Common7\IDE\Ssms.exe» based on the example. 若發生錯誤,將能查看傳回的錯誤碼,以及 %TEMP%\SSMSSetup 中的記錄檔。If something went wrong, you could inspect the error code returned and take a peek at the %TEMP%\SSMSSetup for the log file.

Запрос к таблице и просмотр результатовQuery the table and view the results

Результаты запроса выводятся под текстовым окном запроса.The results of a query are visible below the query text window. Чтобы запросить таблицу Customers и просмотреть ранее вставленные строки, сделайте следующее.To query the Customers table and view the rows that were previously inserted, follow these steps:

  1. Вставьте следующий фрагмент кода T-SQL в окно запросов и нажмите кнопку Выполнить.Paste the following T-SQL code snippet into the query window, and then select Execute:

    Результаты запроса отображаются под областью, где был введен текст:The results of the query are displayed under the area where the text was entered:

  2. Вы можете изменить представление результатов следующими способами.Modify the way results are presented by selecting one of the following options:

    • Кнопка посередине отображает результаты в представлении сетки; это параметр по умолчанию.The middle button displays the results in Grid View, which is the default option.
    • Первая кнопка отображает результаты в текстовом представлении, как показано на снимке в следующем разделе.The first button displays the results in Text View, as shown in the image in the next section.
    • Третья кнопка позволяет сохранить результаты в файл, по умолчанию имеющий расширение .RPT.The third button lets you save the results to a file whose extension is .rpt by default.

Download SSMS

SSMS 18.6 is the latest general availability (GA) version of SSMS. If you have a previous GA version of SSMS 18 installed, installing SSMS 18.6 upgrades it to 18.6.

Version information

  • Release number: 18.6
  • Build number: 15.0.18338.0
  • Release date: July 22, 2020

If you have comments or suggestions, or you want to report issues, the best way to contact the SSMS team is at SQL Server user feedback.

The SSMS 18.x installation doesn’t upgrade or replace SSMS versions 17.x or earlier. SSMS 18.x installs side by side with previous versions, so both versions are available for use. However, if you have a preview version of SSMS 18.x installed, you must uninstall it before installing SSMS 18.6. You can see if you have the preview version by going to the Help > About window.

If a computer contains side-by-side installations of SSMS, verify you start the correct version for your specific needs. The latest version is labeled Microsoft SQL Server Management Studio 18

Note

If you are accessing this page from a non-English language version, and want to see the most up-to-date content, please visit the US-English version of the site. You can download different languages from the US-English version site by selecting .

АргументыArguments

scriptfile — указывает один или несколько файлов скриптов для открытия.scriptfile Specifies one or more script files to open. Этот параметр должен содержать полный путь к файлам.The parameter must contain the full path to the files.

projectfile — задает открываемый проект скрипта.projectfile Specifies a script project to open. Этот параметр должен содержать полный путь к файлу проекта скрипта.The parameter must contain the full path to the script project file.

solutionfile — задает открываемое решение.solutionfile Specifies a solution to open. Этот параметр должен содержать полный путь к файлу решения.The parameter must contain the full path to the solution file.

Имя сервера. Server name

Имя базы данных. Database name

Подключение с использованием аутентификации Azure Active Directory. Connect using Active Directory Authentication. Тип подключения зависит от того, включен ли параметр -U.The type of connection is determined whether -U is included.

Примечание

Проверка подлинности Active Directory — универсальная с поддержкой MFA сейчас не поддерживается.Active Directory — Universal with MFA support is not currently supported.

 — имя пользователя при подключении с использованием проверки подлинности SQL. User name when connecting with ‘SQL Authentication’

 — пароль при подключении с использованием проверки подлинности SQL. Password when connecting with ‘SQL Authentication’

 — подключение с помощью проверки подлинности Windows. Connect using Windows Authentication

 — отключает отображение экрана-заставки при открытии среды SQL Server Management StudioSQL Server Management Studio. Prevents SQL Server Management StudioSQL Server Management Studio from displaying the splash screen graphic while opening. Используйте этот параметр при соединении с компьютером, где среда SQL Server Management StudioSQL Server Management Studio работает с помощью служб терминалов, через соединение с ограниченной пропускной способностью.Use this option when connecting to the computer running SQL Server Management StudioSQL Server Management Studio by means of Terminal Services over a connection with a limited bandwidth. При записи этого аргумента регистр символов не учитывается, он может быть указан до или после других аргументовThis argument is not case-sensitive and may appear before or after other arguments

? ] — записывает действия среды SQL Server Management StudioSQL Server Management Studio в указанный файл для диагностики неисправностей.?] Logs SQL Server Management StudioSQL Server Management Studio activity to the specified file for troubleshooting

 — отображает справку командной строки. Displays command-line help

Supported SQL offerings

  • This version of SSMS works with all supported versions of SQL Server 2008 — SQL Server 2019 (15.x) and provides the greatest level of support for working with the latest cloud features in Azure SQL Database and Azure SQL Data Warehouse.
  • Additionally, SSMS 18.x can be installed side by side with SSMS 17.x, SSMS 16.x, or SQL Server 2014 SSMS and earlier.
  • SQL Server Integration Services (SSIS) — SSMS version 17.x or later doesn’t support connecting to the legacy SQL Server Integration Services service. To connect to an earlier version of the legacy Integration Services, use the version of SSMS aligned with the version of SQL Server. For example, use SSMS 16.x to connect to the legacy SQL Server 2016 Integration Services service. SSMS 17.x and SSMS 16.x can be installed side by side on the same computer. Since the release of SQL Server 2012, the SSIS Catalog database, SSISDB, is the recommended way to store, manage, run, and monitor Integration Services packages. For details, see SSIS Catalog.

Пример интерактивной команды sqlcmdInteractive sqlcmd example

Ниже приведен пример интерактивного выполнения программы sqlcmd .This is an example of what you see when you run sqlcmd interactively.

При открытии окна командной строки там отображается только одна строка:When you open a Command Prompt window, there is one line similar to:

Это означает, что текущей папкой является , и если задать имя файла, то ОС Windows будет искать его в этой папке.This means the folder is the current folder, and if you specify a file name, Windows will look for the file in that folder.

Для подключения к экземпляру sqlcmd по умолчанию на локальном компьютере введите SQL ServerSQL Server . Командная строка будет выглядеть следующим образом:Type sqlcmd to connect to the default instance of SQL ServerSQL Server on the local computer, and the contents of the Command Prompt window will be:

Это означает, что вы подключились к экземпляру SQL ServerSQL Server и что программа готова обрабатывать инструкции Transact-SQLTransact-SQL и команды .This means you have connected to the instance of SQL ServerSQL Server and is now ready to accept Transact-SQLTransact-SQL statements and commands. Мерцающий знак подчеркивания после является приглашением , отмечающим местоположение вводимых инструкций и команд.The flashing underscore after the is the prompt that marks the location at which the statements and commands you type will be displayed. Теперь введите USE AdventureWorks2012 и нажмите клавишу ВВОД, а затем введите GO и снова нажмите клавишу ВВОД.Now, type USE AdventureWorks2012 and press ENTER, and then type GO and press ENTER. Содержимое окна командной строки будет выглядеть следующим образом.The contents of the Command Prompt window will be:

Результирующий набор:Here is the result set.

После ввода команды и нажатия клавиши ВВОД программа получила команду начать новую строку.Pressing ENTER after entering signaled to start a new line. Нажатие клавиши ENTER после ввода дает сигнал программе к отправке инструкции экземпляру SQL ServerSQL Server.Pressing ENTER, after you type signaled to send the statement to the instance of SQL ServerSQL Server. возвращает сообщение, указывающее, что инструкция успешно завершена, и отображает новое приглашение , которое служит сигналом готовности к вводу новой then returned a message to indicate that the statement completed successfully and displayed a new prompt as a signal to enter a new statement or command.

В следующем примере показано содержимое окна командной строки после ввода инструкции , команды для выполнения и команды для завершения программы :The following example shows what the Command Prompt window contains if you type a statement, a to execute the , and an to exit :

Результирующий набор:Here is the result set.

Строки после — это выходные данные инструкции .The lines after line are the output of a statement. Когда выходные данные сформированы, программа сбрасывает приглашение и отображает .After you generate output, resets the prompt and displays . После ввода команды в строке командная строка приобретает первоначальный вид.After entering at line , the Command Prompt window displays the same line it did when you first opened it. Это означает завершение сеанса .This indicates that has exited its session. Теперь можно закрыть окно командной строки. Для этого введите еще одну команду .You can now close the Command Prompt window by typing another command.

SQL Server Management Studio для решения задач бизнес-аналитикиSQL Server Management Studio for Business Intelligence

Среда Службы Analysis ServicesAnalysis Services предназначена для доступа к службам Службы Integration ServicesIntegration Services, Службы Reporting ServicesReporting Services и SQL Server Management StudioSQL Server Management Studio, а также для их настройки, администрирования и управления ими.To access, configure, manage, and administer Службы Analysis ServicesAnalysis Services, Службы Integration ServicesIntegration Services, and Службы Reporting ServicesReporting Services, use SQL Server Management StudioSQL Server Management Studio. Хотя все три технологии бизнес-аналитики полагаются на среду SQL Server Management StudioSQL Server Management Studio, административные задачи, связанные с каждой из этих технологий, несколько отличаются.Although all three business intelligence technologies rely on SQL Server Management StudioSQL Server Management Studio, the administrative tasks associated with each of these technologies are slightly different.

Примечание

Чтобы создать и изменить решения Службы Analysis ServicesAnalysis Services, Службы Reporting ServicesReporting Servicesи Службы Integration ServicesIntegration Services , воспользуйтесь SQL Server Data Tools (SSDT)SQL Server Data Tools (SSDT), а не SQL Server Management StudioSQL Server Management Studio.To create and modify Службы Analysis ServicesAnalysis Services, Службы Reporting ServicesReporting Services, and Службы Integration ServicesIntegration Services solutions, use SQL Server Data Tools (SSDT)SQL Server Data Tools (SSDT), not SQL Server Management StudioSQL Server Management Studio. SQL Server Data Tools (SSDT)SQL Server Data Tools (SSDT) представляет собой среду разработки, основанную на MicrosoftMicrosoftVisual StudioVisual Studio.is a development environment that is based on MicrosoftMicrosoftVisual StudioVisual Studio.

SQL Server Management StudioSQL Server Management Studio позволяет управлять объектами служб Службы Analysis ServicesAnalysis Services , например выполнять их резервное копирование и обработку.enables you to manage Службы Analysis ServicesAnalysis Services objects, such as performing back-ups and processing objects.

Среда Management StudioManagement Studio позволяет создавать проекты скриптов служб Службы Analysis ServicesAnalysis Services , в которых выполняются разработка и сохранение скриптов с использованием многомерных выражений (MDX), расширений интеллектуального анализа данных (DMX) и XML для аналитики (XMLA).provides an Службы Analysis ServicesAnalysis Services Script project in which you develop and save scripts written in Multidimensional Expressions (MDX), Data Mining Extensions (DMX), and XML for Analysis (XMLA). Проекты скриптов служб Службы Analysis ServicesAnalysis Services используются для выполнения задач управления или повторного создания баз данных, кубов и других объектов в экземплярах служб Службы Analysis ServicesAnalysis Services .You use Службы Analysis ServicesAnalysis Services Scripts projects to perform management tasks or re-create objects, such as database and cubes, on Службы Analysis ServicesAnalysis Services instances. Например, можно разработать скрипт XMLA в проекте скрипта служб Службы Analysis ServicesAnalysis Services , который создает объекты непосредственно в существующем экземпляре служб Службы Analysis ServicesAnalysis Services .For example, you can develop an XMLA script in an Службы Analysis ServicesAnalysis Services Script project that creates new objects directly on an existing Службы Analysis ServicesAnalysis Services instance. Проекты скриптов служб Службы Analysis ServicesAnalysis Services могут быть сохранены в составе решения и интегрироваться с контролем исходного кода.The Службы Analysis ServicesAnalysis Services Scripts projects can be saved as part of a solution and integrated with source code control.

Дополнительные сведения об использовании среды SQL Server Management StudioSQL Server Management Studioсм. в разделе Разработка и реализация с помощью среды SQL Server Management Studio.For more information about how to use SQL Server Management StudioSQL Server Management Studio, see Developing and Implementing Using SQL Server Management Studio.

Создание скриптов для расширенных событийScript extended events

В этом разделе описывается, как создать скрипты для расширенных событий.This section covers how to script out extended events.

  1. Подключитесь к серверу SQL Server.Connect to a server that’s running SQL Server.

  2. Разверните узел Управление.Expand your Management node.

  3. Разверните узел Расширенные события.Expand your Extended Events node.

  4. Разверните узел Сеансы.Expand your Sessions node.

  5. Щелкните правой кнопкой мыши нужный расширенный сеанс и выберите пункты Создать скрипт для сеанса > СОЗДАТЬ в > Новое окно редактора запросов:Right-click the extended session you’re interested in > Script Session As > CREATE To > New Query Editor Window:

  6. В новом окне редактора запросов измените имя сеанса с system_health на system_health2.In the New Query Editor Window, modify the new name of the session from system_health to system_health2. Выберите команду Выполнить, чтобы выполнить запрос.Select Execute to execute the query.

  7. Щелкните правой кнопкой мыши Сеансы в обозревателе объектов.Right-click Sessions in Object Explorer. Выберите команду Обновить, чтобы увидеть новый сеанс расширенного события.Select Refresh to see your new extended event session. Зеленый значок рядом с сеансом означает, что сеанс выполняется.The green icon next to the session indicates the session is running. Красный значок указывает, что сеанс остановлен.The red icon indicates the session is stopped.

    Примечание

    Вы можете запустить сеанс, щелкнув его правой кнопкой мыши и выбрав команду Запустить.You can start the session by right-clicking it and selecting Start. Так как это копия уже запущенного сеанса system_health, этот шаг можно пропустить.However, this is a copy of the already running system_health session, so you can skip this step. Вы можете удалить копию расширенного сеанса события, щелкнув его правой кнопкой мыши и выбрав команду Удалить.You can delete the copy of the extended event session: right-click it and select Delete.

Получение sqlpackage для WindowsGet sqlpackage for Windows

Этот выпуск sqlpackage включает стандартные средства установщика Windows и ZIP-файл:This release of sqlpackage includes a standard Windows installer experience, and a .zip:

  1. Скачайте и запустите установщик DacFramework.msi для Windows.Download and run the DacFramework.msi installer for Windows.
  2. Откройте новое окно командной строки и запустите файл sqlpackage.exe.Open a new Command Prompt window, and run sqlpackage.exe

    Программа sqlpackage устанавливается в папку C:\Program Files\Microsoft SQL Server\150\DAC\bin.sqlpackage is installed to the C:\Program Files\Microsoft SQL Server\150\DAC\bin folder

Общие компонентыCommon Components

Все редакторы в среде Среда Management StudioManagement Studio совместно используют следующие компоненты.All of the editors in Среда Management StudioManagement Studio share these components:

Панель кодаCode PaneОбласть, в которой вводятся запросы или текст.The area where you enter your queries or text. В редакторах запросов содержатся функции построителя инструкций, доступные для выбранного языка.In the query editors, it contains the statement builder features available for your language. Среда изменения текста поддерживает поиск и замену, комментирование блоков, а также пользовательские шрифты и цвета.The text editing environment supports find and replace, bulk commenting, and custom fonts and colors.

На панели кода можно установить параметры работы с текстом: отступы, табуляции, режим перетаскивания текста и т. п.You can set options that affect the behavior of text in the code pane as it relates to indenting, tabbing, dragging and dropping of text, and so forth. Окна запросов можно настроить на работу в виде вкладок окна документа или на работу в виде отдельных документов.Query windows can be configured to operate as either tabs in the document window, or in separate documents.

Поле выделенияSelection MarginПустой столбец между границей поля и текстом кода, при щелчке на котором производится выделение текста.A column of white space between the margin indicator bar and the code text where you can click to select lines of text. Можно скрыть или отобразить поле выделения.You can hide or display the selection margin.

Горизонтальные и вертикальные полосы прокруткиHorizontal and Vertical Scroll BarsПозволяют прокручивать код по горизонтали и по вертикали для просмотра кода, выходящего за пределы отображаемой панели.Allows you to scroll the code pane horizontally and vertically so that you can view the code that extends beyond the viewable edges of the code pane.

Нумерация строкLine NumberingОтображает номера строк в редакторе слева от строк текста или кода.Displays line numbers to the left of the text or code in the Editor. Возможно перемещение на конкретные номера строк.You can navigate to specific line numbers.

Перенос по словамWord WrapОтображает длинные строки текста на нескольких строках, позволяя видеть весь текст, содержащийся в строке.Displays long lines of text or code as multiple lines, enabling you to see all the text on the line. Перенос по словам не влияет на внешний вид текста при выполнении или печати.Word wrap does not affect the way text appears when it is executed or printed. Перенос по словам включается в диалоговом окне Параметры(меню Сервис ) на странице «Текстовый редактор», «Все языки», «Общие» или на конкретной странице редактора.Word wrap is turned on from the Tools, Options dialog box, on either the Text Editor, All Languages, General page, or on a specific editor page.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *

Adblock
detector