Перейти к содержимому

Как добавить базу в sql server management studio

  • автор:

Create SQL Server Database using SQL Server Management Studio

You’re new to SQL Server and need to create a database. It sounds like a simple enough task, but how do we do it?

Solution

Let’s step through the database creation process using SQL Server Management Studio (SSMS).

Note: If you’re creating a database for the very first time and you have the rights to do it, it’s assumed you’re doing it on a test or development server and not on a production server.

Versions used here are:

  • SQL Server 2017 Cumulative Update (CU) 16 Developer Edition installed on my laptop
  • SQL Server Management Studio version 18.2 (latest as of this writing)

First, a little background on SSMS. It’s the primary tool used to manage SQL Server. It comes with a vast amount of functionality built in to manage servers and develop SQL scripts. It started life as SQL Server Enterprise Manager and grew into SSMS as of version 2005. And prior to SQL Server 2016, SSMS was packaged with the SQL Server install media and it required the media to install it. As of SQL Server 2016 it’s now a separate download. And even better, it’s free. You can find the documentation and download link to the latest version here. SSMS has a short development cycle and new versions come out about every couple of months or so and the latest version will support all supported versions (and probably unsupported ones as well but we don’t have any of those in our environment of course) of SQL Server. To install it, just click on the download link to get the installer. Execute SSMS-Setup-ENU.exe as an administrator and follow the prompts. It takes a little while to complete but when it’s done, you’ll have the latest SSMS on your machine.

Now that we know what the tool is and where it came from, we can get to work.

Creating a SQL Server Database with SSMS

  1. All Apps
  2. Microsoft SQL Servers Tools
  3. Microsoft SQL Server Management Studio

Start SQL Service Management Studio (SSMS)

  1. Click Connect in the Object Explorer and choose Database Engine…

Connect to database engine

  1. Enter SQL Server name you’re creating database on
  2. Choose authentication method
  3. Enter credentials (if you choose Windows Authentication this will automatically be populated with your Windows credentials) that has rights to create databases

Connect to SQL Server

  1. Right click on Databases
  2. New Database…

New database

  1. Enter database name (this will populate the Logical Name fields)
  2. Leave owner as <default> and you will be the owner or enter another login if needed

New database general options

You could just click OK and the database will be created with the defaults. However, we probably want to go a bit further before doing the create as the default settings aren’t necessarily the best settings, so let’s continue.

Additional New SQL Server Database Configuration Options

  1. Database Name
  2. Owner
  3. Set data file size to determine the initial file size of the data file – You could just leave it at the default, but it’s best it’s best to size it according to what you think it needs initially so it won’t automatically grow right away.
  4. Set transaction log file size to determine the initial file size of the transaction log file – Same as with the data file, it’s best it’s best to size it according to what you think it needs initially so it won’t automatically grow right away.
  5. Click this ellipse to set how much the data file will automatically grow by in the Change Autogrowth box that opens – SQL Server 2017 defaults to 64 MB. This is better than earlier versions, some of which defaulted to automatically grown by 1 MB at a time which meant there was a performance hit as the transaction stops while the file grows every time the file needed to grow by 1 MB which would be frequently.
  6. Click this ellipse to set how much the log file will automatically grow by in the Change Autogrowth box that opens – Same as data file growth.
  7. Make any changes to path for data file – I’m creating this database on my laptop, so everything is on the C:\ drive. You never want to see this this on a server. Typically, you create data files on one drive, say E:\ and logs on another, maybe F:\. C:\ is for the operating system.
  8. Make any changes to path for log file – As stated in the previous step I’m creating this database on my laptop, so everything is on the C:\ drive, but it bears repeating.
  9. Options for additional options see the next image below:

Name new database plus changes to default options

The Options settings will typically remain at the defaults.

  1. But the Recovery model could be changed here in the event transaction log backups are not taken to prevent the log file from growing out of control i.e. the database will be strictly used for testing. Otherwise transaction log backups will be needed.
  2. Change Compatibility Level to a lower version of SQL Server

Other database options

Summary of New SQL Server Database Settings

I’ve named my database MyDatabase, chosen sa as the owner, set initial data file size to 1024MB (1 GB), initial transaction log file size to 512 MB (0.5 GB), data file to automatically grow by 256 MB (0.25 GB) and log file to grow by 128 MB (0.125 GB).

Name new database plus changes to default options with changes made

And on the Options page, I’ve set the Recovery model to Simple as I’m only going to be using this database for some basic testing and won’t be backing up the transaction because there is no point in time recovery needed.

Other database options with changes made

Time to hit OK to create the database.

Check New SQL Server Database in Object Explorer in SSMS

If we look under Databases in SSMS we can see the new database we created called MyDatabase.

Newly created database

  1. Right click on our new database
  2. Choose Properties

Database properties

The Files tab will show us the name, owner, file sizes and autogrow increments we chose. Also, we can see that it chose the physical file names based on the name we chose for the database.

Database properties Files tab

And the Options page shows where we changed the Recovery model to Simple.

Database properties Options tab

There are several other options for a database, but we’ll leave that for another tip on another day.

Next Steps

Following are some links to more detailed information on SSMS, creating databases and recovery models:

  • SQL Server Management Studio Tips — MSSQLTips
  • SQL Server Recovery Models — MSSQLTips
  • Create a Database – Microsoft Docs

get scripts

next tip button

About the author

MSSQLTips author Joe Gavin Joe Gavin is from the Greater Boston area. He started working with SQL Server and Sybase in 1998 in the financial services industry and has been a SQL Server Database Administrator for a dairy cooperative since 2011. He graduated from Northeastern University in Boston with a Bachelor of Science in Engineering Technology (BSET) degree in Computer Technology. Joe has spoken at the Boston and Providence SQL Saturday events.

Создание и открытие баз данных при помощи SQL

SQL Server Management Studio — современная система анализа баз данных. Для создания БД при помощи SQL Server Management Studio не потребуется много времени и особых знаний. В данной статье представлен порядок действий необходимых для создания базы данных.

С чего начать

Сначала нужно подключится к SQL Server Management Studio, и начать разворачивать необходимый узел. Для этого в SQL Server Management Studio используем раздел База данных. В меню выбираем раздел отвечающий за создание новой базы данных. Даем название и устанавливает стандартные описания для базы данных и сохраняем все внесенные изменения.

Теперь переходим к более тонкой настройке нашей базы данных. В графе Файлы баз данных следует прописать все необходимую информацию, относительности будущих свойств баз данных. Начать следует с особенности сортировки данных. Лучше всего использовать комбинированный анализ, когда информация сначала проходит процедуру отсеивания, сканирования и лишь потом сортирования. Требуемые данные указываются в каталоге, который представляет собой пустые поля для заполнения. Среди изменяемых параметров есть тот, который изменить на собственные параметры невозможно. Полно текстовое индексирование является преднастройкой — данный параметр не доступен для удаления и изменения.

Для того, чтобы добавить файлы в базу данных и составить группу, следует вызвать контекстное меню в SQL Server Management Studio и выбрать вкладку Группа файлов. Добавляем необходимое количество и нажимаем кнопку «Сформировать группу». Для того, чтобы расшить функционал SQL Server Management Studio и добавить еще несуществующие (новые) свойства базы данных, следует перейти к вкладке Расширенные свойства. В данном разделе нажать кнопу Создать и задать название нового свойства. Далее прописываем требуемые параметры свойства и сохраняем.

Как открываются базы данных

Для этого понадобится программное обеспечение Microsoft Office Access. Версия, желательно начиная с 2007. Существует несколько способ открыть файл базы данных. Самый простой способ это запустить сам сохраненный документ двойным нажатием на него. Так же можно открыть необходимый документ внутри самой программы, если она уже запущен. Вкладка Файл→Открыть→Указать файл. Если приложение еще не запущено заходим Пуск→Все программы→Microsoft Office Access. Для того, чтобы открытие документа с базой данных было максимально быстрым, следует создать ярлык данного документа и поместить его на рабочий стол.

Документы могут быть защищены не только паролем, но и системным доступом к ним. Такие документы следует запускать от имени администратора. В противном случае част функция будет недоступна. Некоторые базы данных могут и открыться, но потребовать предоставления расширенного доступа к группам папок (внутри каталогов). Чтобы самому сделать документ с ограничением доступа, следует открыть базу данных и в самой программе найти вкладку Монопольный доступ. Среди перечня свойств, выбираем как именно будет осуществляться ограничение и устанавливаем пароль.

Для одновременного открытия двух документов применимы все те же алгоритмы. Можно открывать два окна программы, и по отдельности открыть в них нужные документы. Как одинаковые, так и разные. Повторюсь — самый простой способ, это создать ярлыки. Сначала запускаем один файл, затем второй. Они откроются в двух, разных окнах программы. Следует отметить, что на двух рабочих окнах дело не заканчивается. Можно открыть и больше. Для большего удобства навигации по ним следует использовать комбинацию клавиш alt+Tab. Это позволит переключаться между активными окнами Операционной Системы.

Import database (SQL file) in SQL Server Management Studio

I’ve created the structure of my database first in PhpMyAdmin and exported it to a .sql file. Now I’m looking everywhere in SQL Server Management Studio where I can import/add the data in a new database.

Does anybody where to look or what to click? I’m using the 2014 version (CTP2)

jarlh's user avatar

Matt's user avatar

4 Answers 4

If you have a .sql file which contains SQL statements, you can just copy and paste the contents (or open the file in a query window) and run it. This assumes it has all of the create table etc. statements to create the schema/structure and not just insert statements for the data.

Check the top of the file to make sure that it is first selecting the correct database, if not add a USE statement to select the correct database.

You didn’t say how big the file was, but if it is quite large and has the insert statements (data as well as schema), then you’ll probably want to run by CLI using sqlcmd command. Much faster and SSMS won’t freak out.

Another alternative option to running the .sql file/code is to set up a data source for mysql and just use odbc to access the database itself.

Bear in mind that there are real and very annoying differences between mysql and t-sql that can make migration a pain. If you’re just creating a few tables, it may not be an issue, but if there are a ton of tables with lots of fields of different data types, you may run into issues.

ОТКЛЮЧЕНИЕ И ПОДКЛЮЧЕНИЕ БАЗЫ ДАННЫХ В SQL SERVER MANAGEMENT STUDIO

SQL-сервер позволяет подключать несколько баз данных, можно использовать одну рабочую, а одну тестовую или временно подключить другую базу данных, чтобы в будущем перенести из неё информацию в главную БД. Когда необходимость в какой-то БД отпадает, её нужно отключать.

Процедура отключения и подключения БД происходит только с помощью специальной программы Management Studio (если это 2000-ый сервер, то подключать можно ещё с помощью программы Attach, см. соответсвующий блог), которую Вам нужно установить, если есть необходимость оперировать с БД. Процесс установки и настройки есть в документации, которую можно загрузить по адресу (глава 2- Установка MS SQL Server Management Studio 2008).

Для отключения или подключения БД необходимо войти под паролем и логином в среду Microsoft SQL Server Management Studio. Так же нужно учитывать, что для отображения подключенных БД в SQL Server 2000 – в поле «Имя сервера» вводим только имя компьютера, а для SQL Server 2005 и SQL Server 2008 в поле «Имя сервера» — имя компьютера и имя екземпляра.

Открыть рисунок

Откроется окно «Среда Microsoft SQL Server Management Studio».

В области «Обозреватель объектов» в ветке «Базы данных» выбираем БД, которую нужно отключить и через контекстное меню «Задачи» -> «Отсоединить» отсоединяем желаемую базу. Нужно учесть, что база не удаляется, она просто отключается от SQL-сервера.

Открыть рисунок

Процедура подключения БД происходит через тоже окно, что и отключение. После того, как мы вошли в окно «Среда Microsoft SQL Server Management Studio» под паролем и логином, станьте на ветку «Базы данных», через контекстное меню выбираем пункт «Присоединить. ».

Открыть рисунок

В появившемся окне указываем местоположение БД, которую нужно присоединить.

Открыть рисунок

Открыть рисунок

В последнем окне видна информация о присоединяемой БД: местоположение БД и название. И нажимаем «Ок» — в результате чего наша база отобразится в «Обозреватели объектов» в директории «Базы данных».

В конечном результате при загрузке GIS 6 и запросе на соединение с базой данных в поле «Базы данных» в ниспадающем списке отобразится наша подсоединённая БД.

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

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