Sql server management studio как подключиться к локальному серверу

Connect to SQL Server Using Management Studio

In this tutorial, let us learn how to connect to SQL Server Using SQL Server Management Studio (SSMS). Using the SQL Server Management Studio is a simple and easy way to connect to the SQL Server Instance.

If you have not installed the SQL Server, then you must visit how to install SQL Server & How to install SQL Server Management Studio tutorials

Table of Contents

Starting SSMS

Start SQL Server Management Studio. You can find it from

Program files -> Microsoft SQL Server Tools 18 -> Microsoft SQL Server Management Studio

SQL Server Management Studio in Program Files

The first time you run SSMS, the Connect to Server window opens.

If it doesn’t open, you can open it manually by selecting Object Explorer > Connect > Database Engine. If Object Explorer is not opened, you can open it from the Menu -> View -> Object Explorer

Object Explorer Menu

Object Explorer

Connect to Server

The Connect to Server window appears as shown below

Server Type: Choose Database Engine to connect to SQL Server database Server.

Server Name: Server Instance Name. Use your computer name if you want to connect to default Instance. Else enter the name as <compuetName>\<InstanceName>

The instance name is the name you have given when you were installing the SQL Server under Instance Configuration.

Authentication: There are two authentication modes. One is Windows & Another one is SQL Server authentication mode. If you choose windows, then the current logged in user is automatically picked by the system.

SQL Server Authentication works only if you have selected the Mixed Mode authentication when you were installing the SQL Server. We set up this while configuring the database engine.

User Name: This is enabled when you choose SQL Server Authentication Mode. If you are connecting to the newly installed SQL Server then the only user you have is sa.

Password: Enter the sa password

Connect to SQL Server Using Windows Authentication

Connect to SQL Server Using SQL Server Authentication

Click on Connect to Connect to the Server

Object Explorer

The SSMS connects to the SQL Server Instance. On Successful connection, you will see the object explorer as shown in the image below.

SQL SERVER Connected Via SQL Server Management Studio

Under the Server Name, you will see various nodes like database, security, management listed. Expand the Databases node to see the list of databases available. In a newly installed server, you won’t see any database except for the System databases.

Summary

We use SSMS to connect to the database. SSMS Provides the GUI tools to explore & Manage a database instance.

Microsoft SQL Server — особенности и установка СУБД MS SQL

Microsoft SQL Server — это РСУБД (система управления реляционными базами данных), которая разработана специалистами из Microsoft. В качестве основного языка запросов используется Transact-SQL (совместная разработка Microsoft и Sybase). При этом Transact-SQL — это реализация стандарта ANSI/ISO по SQL (структурированному языку запросов), но имеющая некоторые расширения. Сегодня СУБД MS SQL широко применяется при работе с базами данных (БД) самых разных размеров, начиная от персональных, заканчивая крупными БД масштаба предприятия.

Немного теории: о СУБД и БД

Само по себе представление о БД (базах данных) различается с учётом того, какая это точка зрения — пользовательская либо системная. В первом случае под БД понимается некая таблица с нужными данными (информацией), отображённая на мониторе либо даже листке бумаги. Во втором случае мы имеем системную, то есть администраторскую точку зрения, исходя из которой БД — это набор файлов, в которых реализованы таблицы и связи между таблицами, и к которым надо организовать доступ со стороны пользователей.

В настоящее время этот самый доступ организуется централизованно. В основе современной технологии лежит взаимодействие сервера и клиента. Клиенты — персональные компьютеры пользователей, серверы баз данных — мощные и высокопроизводительные компьютеры, обеспечивающие одновременный доступ к данным сотен и тысяч пользователей.

Сервер предоставляет данные, а клиенты их запрашивают, что происходит путём отправки клиентом SQL-запроса серверу. Сервер, в свою очередь, выполняет обработку запроса, возвращая запрошенные данные клиенту. Т. к. запрос реализуется на специальном языке SQL, он хорошо понятен и серверу, и пользователю.

Тут следует заметить, что серверы бывают разные и различаются тем, как они: • предоставляют доступ; • хранят данные; • предоставляют данные пользователю.

Соответственно, для каждой из вышеперечисленных целей существует отдельный программный компонент: • прикладные программы — предоставляют доступ и обеспечивают визуализацию; • интерфейс — служит для предоставления данных; • программы взаимодействия с файловой системой — обеспечивают хранение данных.

И вот как раз для взаимодействия программных компонентов и необходим ещё один компонент, называемый СУБД, то есть речь идёт о системе управления базами данных. По сути, СУБД представляет собой программную прослойку между сервером и пользователем. СУБД даёт возможность абстрагировать пользователя от системного видения базы данных, самой же системе предоставляется способ непосредственного взаимодействия с пользователем.

Задачи СУБД: • извлечение данных с диска и сохранение данных на диск; • работа с данными в оперативной памяти сервера; • логирование (журналирование, запись истории изменения БД); • поддержка запросов пользователя в целях определения и манипуляции данными на структурированном языке SQL.

Вышеописанные задачи по взаимодействию с БД решаются с помощью разной реализации компонентов, в результате чего различаются и СУБД, которые бывают иерархические, сетевые, реляционные, объектно-реляционные, объектно-ориентированные.

Кроме того, по способу доступа к БД системы бывают клиент-серверные, файл-серверные и встраиваемые.

Что касается СУБД SQL Server, то она является реляционной и клиент-серверной. Эта СУБД довольно популярна на системах, построенных на базе ОС Windows. Давайте установим и настроим её, взяв для примера SQL Server 2016 Enterprise.

Устанавливаем ПО для работы

В первую очередь, нужно скачать установочный пакет SQL Server 2016 Enterprise, перейдя на официальную страницу. Скачанная вами версия будет бесплатна в течении 180 дней. Также, если вы имеете подписку MSDN, можете использовать SQL Server 2016 Developer Edition.

Итак, софт скачан. Однако прежде, чем запускать установщик, надо создать учётную запись — она позволит авторизоваться на сервере с клиентского ПК. Так как в нашем случае это будет один и тот же компьютер, SQL Server будет аторизовываться через Management Studio, однако его скачаем несколько позже.

Создаём учетную запись

Чтобы создать учетную запись в Windows: 1. Кликаем правой кнопкой мышки значок «Мой компьютер» на рабочем столе, выбираем из списка пункт «Управление». 2. В открывшемся окне «Управление компьютером» выбираем пункт «локальные пользователи», потом выделяем пункт «пользователи». Окно станет такого вида: 20171014152342_image001_1-20219-b1182b.jpg3. Кликаем правой кнопкой мыши на пустое пространство папки либо по названию папки, потом выбираем пункт «новый пользователь», открывается окно: 20171014152458_image002_1-20219-21635c.jpg4. Указываем имя пользователя и пароль, нажимаем «Создать». Лучше всего применять латиницу.

Устанавливаем SQL Server

Алгоритм действий следующий: 1. Запускаем ранее скачанный пакет установки. Должен открыться SQL Server Installation Server: 20171014152545_image003_2-20219-f1b42e.png2. Выбираем пункт «Установка». 3. После изменения экрана кликаем «Новая установка изолированного экземпляра SQL Server». Произойдёт запуск установки. Жмём «Далее». 20171014152629_image004_2-20219-b9f08d.jpg4. Обратите внимание, чтобы на этапе «правил установки» в окне отсутствовали красные крестики. В обратном случае нажимайте на выделенные строки предупреждений и следуйте инструкциям, чтобы их устранить. Потом жмём «Далее», окно установки опять поменяется: 20171014152731_image005_2-20219-24f63d.jpg5. Выбираем «Выполнить новую установку SQL Server 2016», открывается окно регистрации продукта: 20171014152818_image006_2-20219-91720a.jpg6. Вводим лицензионный ключ продукта при наличии. В обратном случае выбираем Evaluation, что активирует 180-дневную копию. 7. Принимаем лицензионное соглашение. 8. Открывается окно компонентов. Устанавливаем галочки напротив: — службы ядра СУБД; — соединение с клиентскими средствами; — компоненты документации. Снова нажимаем «Далее». 20171014153014_image007_2-20219-0cd962.jpg9. Если есть установленная копия SQL Server, выбираем «экземпляр по умолчанию», если нет (устанавливаете впервые) — именованный экземпляр. Вводим в поле имя Экземпляра, жмём «Далее». 2017101415322_image008_2-20219-9ef0f2.jpg10. Проверяем, хватает ли места на диске. Если не хватает, освобождаем его и жмём «Далее». 11. На этапе «Настройка Ядра СУБД» убеждаемся, что выбрали строку «Проверка подлинности Windows». Если не выбрали, выбираем. Потом добавляем в нижнее поле пользователя, которого мы создавали перед установкой (либо добавляем текущего соответствующей кнопкой). Жмём «Далее». 20171014153230_image009_2-20219-36f76a.png12. Перепроверяем все настройки установки системы управления БД SQL Server. 13. Наблюдаем за установкой до её завершения.

Устанавливаем и настраиваем MS SQL Server Management Studio

Итак, сервер к работе готов, теперь надо настроить клиент. Система управления БД MS SQL Server Management Studio предоставляет нам визуальный интерфейс, предназначенный для клиента. Это повышает удобство разработки и отправки запросов.

ПО самостоятельно определит, где у вас находится сервер — достаточно просто следовать инструкциям.

Настраиваем работу в Management Studio

Алгоритм следующий: 1. Находим Management Studio в меню «ПУСК», запускаем. 2. Открывается окно соединения с сервером SQL Server, где выбираем: — Ядро СУБД в поле «Тип сервера»; – имя сервера, указанное вами при установке в поле имя сервера; — Проверка подлинности Windows в поле «Проверка подлинности». 20171014153321_image010_2-20219-c64197.jpg3. Нажимаем «Соединить». В результате Management Studio подключится к SQL Server, и произойдет открытие основного окна программы. Обязательно изучите такой элемент, как «Обозреватель объектов» — он даёт возможность работать со всеми структурными элементами БД на сервере посредством интерфейса, похожего на проводник Windows.

2017101415340_image011_2-20219-f7d4ba.jpg

Чтобы создать новый запрос, кликаем по кнопке «Создать запрос». Запрос сформируется для текущей таблицы, указанной в выпадающем списке сверху (в нашем случае — master).

Кликнув «Создать запрос» несколько раз, мы откроем несколько вкладок. При этом мы можем менять текущую таблицу, используя выпадающий список.

Под полем редактора запросов находится поле результатов. Там показываются результаты выполнения запроса:

20171012142542_12_2-20219-9da21d.jpg

Пожалуй, это всё, что можно рассказать во вводной статье про систему управления базами данных MS SQL SQL. Всему остальному можно научиться во время работы. Или у нас на курсе.

How to connect to a local database in SQL Server Management Studio?

I have downloaded the SQL Server Management Studio (SSMS) 2016 to recover a huge .bak file which is an old backup of a database. But first of all I need to connect to a DB Server.

After install, I execute SSMS and it asks me to connect to a DB Server. I don’t have any and I saw that it is possible to create a «local» db by typing only a dot ‘.’ for Server Name and use Windows authentication.

It is not working; how to do it?

3 Answers 3

  1. Open SSMS -> Connect
  2. Server name: (LocalDb)\MSSQLLocalDB ,
  3. Choose Windows Authentication.

For a reference:

enter image description here

Xin

You need to download and install SQL LocalDB. It is a special edition of SQL Server that does not allow remote connection and supports windows integrated authentication only. It is a simple one click MSI install so it is easy to deploy.

To download and install SQL Server 2016 Express, go to SQL Server downloads. LocalDB is a feature you select during installation, and is available when you download the media. If you download the media, either choose Express Advanced or the LocalDB package.

The above means that now you have to download and run a small downloader (cca 5 MB), select LocalDB (44 MB) and the Microsoft downloader will download MSI package to the folder you select. Then just run MSI package and LocalDB gets installed.

How to connect to your local MSSQL server using SSMS?

This post was most recently updated on June 19th, 2022.

Every now and then you run into a situation, where you really need to run some SQL against your local development database. That database, at least in my case, is hosted on your local SQL Server Express.

Connecting to a local SQL Server should be a walk in a park, right? Eh, well…

While using a connection string to connect to said DB is easy, you can’t do that with the SQL Server Management Studio. I wish you could, but hey – it is what it is.

There’s a couple of ways to connect, though! Let’s start with the easy one, that doesn’t always work:

How to connect to your local database with SQL Server Management Studio?

Table of Contents

Connecting to the local instance might work by using the name of the instance. While I’m not sure what’s the reason it hasn’t worked for me (I wonder if the instance names differs based on what you’re installing the SQL Server or SQL Express with. ), maybe it works for you.

Essentially, just paste this into the connection window:

Or like shown below:

How to log in to local SQL Server database using SQL Server Management Studio.

How to log in to local SQL Server database using SQL Server Management Studio.

Workaround: Use Named Pipes instead

If it doesn’t – well, there’s a workaround, although it’s a bit laborious. It in fact requires you to know the instance name pipe – a weird, nonsensical URI-looking piece of textual vomit you simply can’t guess. And then, most of the time, you can just use your local user account to log in.

The workaround has quite a few steps, and finally comes down to this beautiful screen below:

How to log in to local SQL Server using named pipes.

How to log in to local SQL Server using named pipes.

But how do you figure out the right Server name? Check out the steps below!

Time needed: 10 minutes.

    Try using (localdb)\MSSqlLocalDb first

It won’t hurt testing “(localdb)\MSSqlLocalDb” for Server name – just to see if it works.

The location is something like this under your SQL Server’s installation path -> Tools -> Binn.

Easy enough – run this in your console:
SqlLocalDB.exe

SqlLocalDB.exe output in console.

The tool should output something like this:

Next, let’s run the command with parameter “info”.
> SqlLocalDB info
MSSQLLocalDB
ProjectsV13

Now we’ll get to actually run the command for our instance. This’ll look somewhat like below:
SqlLocalDB info [instancename]

You’ll want to get this server up and running. That’s easy – just run the command below:
SqlLocalDB start MSSQLLocalDB

The output might be something like below:

Or in text form:
SqlLocalDB info MSSQLLocalDB
Name: MSSQLLocalDB
Version: 13.1.4001.0
Shared name:
Owner: [username]
Auto-create: Yes
State: Running
Last start time: 2020-08-12 1:22:49 PM
Instance pipe name: np:.\pipe\LOCALDB#A4E758FA\tsql\query

Pay very close attention to the state – it should now be “running” – and note “Instance pipe name“!

And boom! You should be good.

References and appendices

Updated 13.2.2020: Added mention of the easier method (hopefully that works for y’all!), thanks Mika Berglund.

For further reference, check out these links:

Appendix 1: the output of SqlLocalDB.exe

I’m including the whole default output of SqlLocalDB.exe here, as it won’t fit into the step-by-step instructions above.

Antti Koskela is a proud digital native nomadic millennial full stack developer (is that enough funny buzzwords? That’s definitely enough funny buzzwords!), who works as Solutions Architect for Precio Fishbone, building delightful Digital Workplaces.

He’s been a developer from 2004 (starting with PHP and Java), and he’s been working on .NET projects, Azure, Office 365, SharePoint and a lot of other stuff. He’s also Microsoft MVP for Office Development.

This is his personal professional (e.g. professional, but definitely personal) blog.

    — September 20, 2022 — September 13, 2022 — September 6, 2022
Posts Related to «How to connect to your local MSSQL server using SSMS?»:

report this ad

Search this site!

Author

About the site and the author

Welcome! You just stumbled upon the home page of an all-around artisan code crafter and Microsoft MVP, Antti «koskila» Koskela.

Don’t hesitate to leave comments. I read them all and try to reply as well!

More information about me in the About -section!

Solutions are worthless unless shared!

Check out the tech & programming tips, often about ASP.NET MVC, Entity Framework, Microsoft SharePoint Server & Online, Azure, Active Directory, Office 365 or other parts of the ever-growing and more and more intimidating stack that Microsoft offers us.

I’ve been developing both classic server stuff, but also (and actually especially) more cloud-oriented stuff in the past 15 years.

There’s an occasional post about software issues other than on Microsoft’s stack, and a rare post about hardware, too! And sometimes I might post about my sessions at different community events, or experiences as an expat living in a foreign country (in 2017, that country was the USA, in 2018 & 2019 Canada).

And since I’m hosting this site on WordPress, and boy does WordPress experience a lot of issues, I might also post something about solving those cases. Like PHP compatibility issues.

report this ad

Want the latest tips directly to your inbox?

Like these posts and tips? You can get them automatically right as I post them! Enter your email here or check out the RSS feed here: https://www.koskila.net/feed/

And no worries — it’s just notifications of new posts coming in, nothing else 🙂

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

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