Microsoft SQL Server: работа с базами данных
Наши пользователи могут использовать базы данных Microsoft SQL Server 2016 на своих виртуальных площадках в рамках, предусмотренных соответствующими тарифами.
Параметры и способы соединения с Microsoft SQL Server
- Имя хоста (сервера), на котором размещена база данных Microsoft SQL Server: uXXXXX.mssql.masterhost.ru;
- Порт: 1433;
- Логин: соответствует названию виртуальной площадки — uXXXXX;
- Пароль: указан в письме, которое пользователь получает при регистрации;
- Имя базы данных: соответствует названию виртуальной площадки — uXXXXX;
- Подключение нужно осуществлять по протоколу TCP/IP.
Подключение к SQL-серверу через «Microsoft SQL Server Management Studio Express»
Чтобы получить доступ к базе данных Microsoft SQL Server, возможно использовать Microsoft SQL Server Management Studio Express .
В параметрах выберите в качестве сетевого протокола TCP/IP.
Создание новой базы данных
Новую базу данных вы можете создать через раздел Услуги, в Личном кабинете. Выберите нужную «виртуальную площадку», далее в разделе «MS SQL» нажать на кнопку «+ База MS SQL». Затем вам необходимо указать имя (логин) и выбрать владельца новой базы.
Использовать Microsoft SQL Server Management Studio для создания новых баз данных нельзя.
Создание нового логина
Создать новый логин для базы данных Microsoft SQL вы можете через раздел Услуги, в Личном кабинете. Выберите нужную «виртуальную площадку», далее в разделе «MS SQL» нажать на кнопку «+ Пользователь MS SQL». Затем вам необходимо указать имя (логин) для нового пользователя.
Уменьшение физического размера файлов баз данных и лога транзакций MS SQL Server.
Из графического интерфейса Microsoft SQL Server Management Studio:
- В обозревателе объектов подключитесь к экземпляру Microsoft SQL Server, 2016 Web Edition и разверните его.
- Разверните узел «Базы данных», затем правой кнопкой мыши щелкните базу данных, которую нужно сжать.
В меню «Задачи» выберите «Сжать» и щелкните «База данных». Или установите флажок «Реорганизовать файлы перед освобождением неиспользуемого места».
Если он установлен, необходимо указать значение параметра «Максимально доступное свободное место в файлах после сжатия».
Стандартным t-sql запросом вида:
где uXXXXX — имя вашей базы данных.
Изменение кодировки сравнения (collation)
По умолчанию кодировка collation выставлена как Cyrillic_General_CI_AS, изменить кодировку для сравнений можно следующим SQL-запросом:
где uXXXXX — имя БД, где требуется данная операция.
Список доступных кодировок можно узнать так:
Как дать права на доступ к базе определенному логину
Для SQL — дополнительный SQL логин, но настраивать права нужно самому: Заводим еще один SQL логин — uXXX_Ann
Для начала используем нашу базу:
Создаем пользователя для определенного «логина»:
Наделяем его правами (например только чтение таблиц):
Или можем дать пользователю только конкретные права, на конкретные таблицы. Например, давайте дадим пользователю InetUser права на SELECT, INSERT, UPDATE для таблицы test, следующим SQL-запросом :
При всем при этом, при осуществлении доступа через SQL Management Studio, под дополнительным логином не являющимся владельцем базы, не будет видно базу данных в списке доступных баз, но будет возможность выполнять разрешенные SQL-запросы .
How to enable remote connections to SQL Server
So you have a VM or a remote server, that you have installed SQL Server, but you also want to connect to SQL Server using SQL Server Management Studio on your local system, but gives you this error.
This is because you haven’t configured it to allows inbound connections from firewall or from SQL Server itself, could be both.
Prerequisites
- Remote server/VM must have SQL Server Management Studio and SQL Server Configuration Manager Installed.
- Remote SQL Server must have a user that have read and write privileges (Here I’m using sa user)
All set, let’s start
Connect to the server/VM using Remote Desktop Connection and open up SQL Server Management Stdio on remote server, then connect to the SQL Server instance.
Now right click on the server and go to Properties.
On the Connections page under Remote server connections, make sure that the Allow remote connections to this server is checked.
Now open SQL Server Configuration Manager.
Visit Protocols for <instance name>, in my case Protocols for MSSQLSERVER under SQL Server Network Configuration node, go to TCP/IP and make sure the ‘Status’ is set to Enabled. If not, right click and select Enable.
After that, again right click and select Properties of TCP/IP protocol.
Goto IP Addresses tab and go down until you see IPALL section. Make sure the TCP Port is set to 1433. If not set it to 1433.
This warning will appear, so we need to restart the server. we can do it by using SQL Server Configuration manager.
Locate SQL Server under SQL Server Services, right click and select Restart.
Now lets configure the firewall.
Open up Windows Firewall.
Go to Inbound Rules and select New Rule.
Add the following rule. Follow images if unclear.
Rule Type: Port
Protocol and Ports: TCP, 1433
Action: Allow the connection
Profile: Domain, Private, Public
Name: SQLTCP1433
Click finish. We need to add another rule for UDP connections as well.
Rule Type: Port
Protocol and Ports: UDP, 1434
Action: Allow the connection
Profile: Domain, Private, Public
Name: SQLUDP1434
Let’ make SQL Server and SQL Server Browser accessible through firewall.
Rule Type: Program
Program: C:\Program Files\Microsoft SQL Server\<Server version>.<Instance name>\MSSQL\Binn\sqlservr.exe
e.g. C:\Program Files\Microsoft SQL Server\MSSQL14.MSSQLSERVER\MSSQL\Binn
Action: Allow the connection
Profile: Domain, Private, Public
Name: SQLSERVER
Connect to the SQL Server
Summary: in this tutorial, you will learn how to connect to SQL Server from the SQL Server Management Studio and execute a query.
Connect to the SQL Server using SSMS
To connect to the SQL Server using the Microsoft SQL Server Management Studio, you use these steps:
First, launch the Microsoft SQL Server Management Studio from the Start menu:
Next, from the Connect menu under the Object Explorer, choose the Database Engine…
Then, enter the information for the Server name (localhost), Authentication (SQL Server Authentication), and password for the sa user and click the Connect button to connect to the SQL Server. Note that you should use the sa user and password that you entered during the installation.
If the connection is established successfully, then you will see the following Object Explorer panel:
Execute a query
To execute a query you follow these steps:
First, right-click on the localhost (SQL Server …) node and choose the New Query menu item:
Second, enter the following query in the Editor
This query returns the version of the SQL Server.
Third, click the Execute button:
The Results window shows the version of the SQL Server as shown in the above screenshot. A quick way to execute a query is to press the F5 keyboard shortcut.
Now, you should know how to connect to a SQL Server and execute a query from the SSMS.
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
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
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
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.
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.