Ms sql examples. Executing SQL queries in Management Studio

Ms sql examples. Executing SQL queries in Management Studio

11.05.2021

Develop an application that demonstrates the basic operations on data in a database of the MS SQL Server type, namely:

  • database connection to the application;
  • displaying database tables on a form;
  • adding a new record to the database;
  • editing a record;
  • deleting an entry.

Based on the Education.dbo database, the creation process of which is described in detail

Figure 1 shows the structure of the Education.dbo database. As you can see from the figure, the database is called:

sasha-pc\sqlexpress.Education.dbo

Here " sasha-pc"- the identifier of the computer on the network," sqlexpress"- the name of the database server," Education.dbo"- the name of the database.

Rice. 1. Education.dbo database

The database contains two tables: Student and Session. The table structure is as follows.

The Student table.

Session table.

Performance

1. Create a new project in MS Visual Studio as Windows Forms Application.

Create a new project Windows type Form Application . An example of creating a new project is described in detail

2. Create a new view ( view ) to display data from the Student table.

To display database table data, you can use different ways. One of them is the creation of views (views), which are formed by means of MS Visual Studio.

In our case, the table data will be displayed on the form in a DataGridView control. After creating the views, it is very convenient to associate them with the elements of the DataGridView .

To create a view, you need to call the command " Add New View"From the context menu, which is invoked by right-clicking on the element" Views"Education.dbo database (Figure 2).

Rice. 2. Calling the command to add a new view

As a result, the "Add Table" window will open (Figure 3). In the window, you need to select the tables that are added to the view.

Rice. 3. Selecting the tables on which the new view will be based

In our case, select the Student table and confirm your choice by clicking on the Add button. The next step is to close the window by selecting the Close button.

After the performed actions, a window will be generated in which you need to select the fields that should be displayed in the view (on the form). Select all fields (Figure 4).

When selecting fields, the fields of the Student table are displayed at the top of the workspace. With the help of the "mouse" you can select the desired fields for presentation.

Accordingly, in the middle area of ​​the window, the names of the selected fields, the table in which they are present (see Fig. 4), the possibility of sorting, filtering, and so on are displayed.

At the bottom of the pane, the corresponding SQL query text is displayed, which is used to create the view.

Rice. 4. Select fields of the Student table to display in the view

After team selection

File->Save All File->Save View1

A window will open asking you to enter a name for the view. Set the name " View student"(Figure 5).

Rice. 5. Specify a name for the view

After the performed actions, the view window will look as shown in Figure 6.

Rice. 6. Representing View Student in the database

Now you can host the DataGridView control and bind it to the view.

3. Placing the DataGridView control and setting up a connection to the database.

Before placing the DataGridView control, you need to switch to Form1.cs form design mode.

The DataGridView is a table that can display data. This control is placed in the ToolBox panel. First, we slightly adjust the size of the form, and then place the DataGridView control on it (Figure 7). This will create an instance of an object named dataGridView1 by default.

Rice. 7. DataGridView control and data source selection window

After placing a control of type DataGridView on the form in the upper right corner, you can select the data source setting. Accordingly, the "DataGridView Tasks" window will open. In this window, you need to select the "Choose Data Source" pop-up menu.

In the menu that opens, the command “Add Project Data Source…” is selected (Fig. 7). After that, a wizard window opens, in which the data source is sequentially selected.

Figure 8 shows the window " Data Source Configuration Wizard", in which the type of data source is selected. In our case, install "Database".

Rice. 8. Selecting the type of data source

In the next window (Figure 9), the data source model is selected. You need to select DataSet .

Rice. 9. Selecting a Data Source Model

In the window shown in Figure 10, you need to specify the data connection that you want to use to connect to the database. In our case, we need to select the database " sasha-pc\sqlexpress\Education.dbo«.

Rice. 10. Selecting a data connection

The next window (Figure 11) prompts you to save the Connection String to the application's configuration file. Leave everything as it is and move on to the next window.

Rice. 11. Proposal to save the connection string with the database Connection String in the application configuration file

After creating a database connection, a lot of database objects are displayed (Figure 12). In our case, we need to select the View Student and all fields from it. The checked fields will be displayed in the DataGridView .

Rice. 12. Selecting database objects to display in the DataGridView

After selecting the Finish button, the selected objects (View Student view) of the Education.dbo database will be displayed (Figure 13).

Rice. 13. DataGridView control with selected View Student view fields

Similarly, you can set up views that contain any fields from any database tables. Also, fields from different tables can be displayed in one view.

4. Customizing the appearance of the DataGridView control.

If you run the application for execution, then the View Student view data will be received, which corresponds to the database Student table (Figure 14).

Rice. 14. Launching the application for execution

As you can see from Figure 14, the data in the dataGridView1 table is displayed normally, but the design can be adjusted.

The control of the DataGridView type allows you to adjust the appearance of the fields that are displayed.

To call commands for editing fields, just call the context menu by right-clicking on the dataGridView1 control.

There are various useful commands in the menu that allow you to control the appearance and operation of the DataGridView :

  • command to lock the control (Lock Controls );
  • command for editing fields that are displayed in the view (Edit Columns…);
  • command for adding new fields, for example, calculated ones (Add Column).

In our case, you need to select the command "Edit Columns ..." (Figure 15).

Rice. 15. The command "Edit Columns ..." from the context menu

As a result, the “Edit Columns” window will open, in which you can customize the appearance of the view fields to your liking (Figure 16).

Rice. 16. Window for setting the type of fields in the view "View Student"

In the window in Figure 16, for any field, you can set the name, alignment, width, the ability to edit data, etc.

5. Connection String

In order to make changes to the database, you need to get the connection string with the database Connection String .

There are different ways to get the database connection string. One of them is based on reading this line in the Properties window of the Education.dbo database (Figure 17).

Rice. 17. Defining a Connection String

To save the string in the program, an internal variable of the type string. Using the clipboard, copy the Connection String to the described variable of the string type.

In the text of the file " Form1.cs" At the beginning of the description of the Form1 class, you must describe the variable:

string conn_string = ;

At the moment, the text of the Form1 class is as follows:

public partial class Form1 : Form { string conn_string = @"Data Source=(local)\SQLEXPRESS;Initial Catalog=Education;Integrated Security=True;Pooling=False"; public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { // TODO: This line of code loads data into the "educationDataSet.View_Student" table. You can move, or remove it, as needed. } }

6. Creation of a new form to demonstrate data manipulation commands.

In order to be able to process the data of the current record, you need to create a new form. The process of creating a new form in MS Visual Studio - C# is described in detail.

Adding a new form is done with the command:

Project -> Add Windows Form...

In the window that opens " New Item"You need to select the element" Windows Form«.

We leave the file name of the new form by default "Form2.cs".

Figure 18 shows a view of the new form.

We place controls of the following types on the form:

  • two controls of type Button (buttons OK and Cancel ). Accordingly, two objects will be obtained with the names button1 and button2 ;
  • four controls of the Label type for creating informational messages;
  • four controls of type TextBox for entering data in the fields Num_book , Name , Group , Year .

You need to set the following properties of controls:

  • in the control button1 property Text = "OK";
  • in the control button2 property Text = "Cancel";
  • in the control button1 property DialogResult = "OK";
  • in the button2 control, property DialogResult = "Cancel";
  • in the control label1 property Text = "Num_book";
  • in the control label2 property Text = "Name";
  • in the control label3 property Text = "Group";
  • in the label4 control, the property Text = "Year".

We also set the visibility of controls of type TextBox . To do this, in all controls textBox1 , textBox2 , textBox3 , textBox4 property value Modifiers = " public ".

Rice. 18. View of the newly created form

7. Adding buttons for calling commands for manipulating the data of the Student table.

For further work, you need to switch to the main form Form1 with the mouse.

We add three buttons to the main form of the Form1 application ( Button ). Three object variables named button1 , button2 , button3 will be automatically created. In each of these buttons we make the following settings (Properties window):

  • in the button button1 property Text = "Insert ..." (insert record);
  • in the button button2 property Text = "Edit ..." (change entry);
  • in the button button3 property Text = "Delete".

As a result of the changes made, the main form will look as shown in Figure 19.

Rice. 19. Application main form

8. Programming the click event on the “Insert…” button.

The click event handler for the Insert… button looks like this:

private void button1_Click_1(object sender, EventArgs e) { string cmd_text; Form2 f2 = new Form2(); if (f2.ShowDialog() == DialogResult .OK) { cmd_text = "INSERT INTO Student VALUES (" + """ + f2.textBox1.Text + "" , "" + f2.textBox2.Text + "" , "" + f2.textBox3.Text + "" , " + f2.textBox4.Text + ")" ; // create a database connection SqlConnection sql_conn = new SqlConnection(conn_string); // create command in SQL language SqlCommand sql_comm = new SqlCommand(cmd_text, sql_conn); sql_conn.Open(); // open connection sql_comm.ExecuteNonQuery(); // execute command in SQL language sql_conn.Close(); // close the connection this .view_StudentTableAdapter.Fill(this .educationDataSet.View_Student); } }

First, Form2 is called. After receiving the result "OK" (pressing the corresponding button), in Form2, the filled fields in elements of the TextBox type are included in the SQL query string. The SQL query for adding a new row looks like this:

INSERT INTO Student VALUES (value1, value2, value3, value4)

where value1 corresponds to the number of the grade book; value2 – student's last name; value3 - the group in which the student is studying; value4 – entry year.

The connection string with the database Connection String is described in the conn_string variable (see item 5). The SqlConnection class object connects the application to data sources. In addition, the Connection class handles user authentication, networking, database identification, connection buffering, and transaction processing.

The SQL command that adds a record to a table is encapsulated in the SqlCommand class. The constructor of the SqlCommand class takes two parameters: an SQL query string (cmd_text variable) and an object of the SqlConnection class.

The ExecuteNonQuery() method is implemented in the IDBCommand interface. The method implements SQL commands that do not return data. These commands include INSERT , DELETE , UPDATE commands, as well as stored procedures that do not return data. The ExecuteNonQuery() method returns the number of records involved by it.

9. Programming the click event on the “Edit…” button.

The click event handler on the button "Edit ..." looks like this:

private void button2_Click(object sender, EventArgs e) ( string cmd_text; Form2 f2 = new Form2 (); int index; string num_book; index = dataGridView1.CurrentRow.Index; num_book = Convert .ToString(dataGridView1.Value); f2.textBox1 .Text = num_book;f2.textBox2.Text = Convert .ToString(dataGridView1.Value); f2.textBox3.Text = Convert .ToString(dataGridView1.Value); f2.textBox4.Text = Convert .ToString(dataGridView1.Value); if (f2.ShowDialog() == DialogResult .OK) ( cmd_text = "UPDATE Student SET Num_book = ""+ f2.textBox1.Text + "", " + " = "" + f2.textBox2.Text + "", " + " = "" + f2.textBox3.Text + "", " + "Year = " + f2 .textBox4.Text + "WHERE Num_book = "" + num_book + """ ; SqlConnection sql_conn = new SqlConnection(conn_string); SqlCommand sql_comm = new SqlCommand(cmd_text, sql_conn); sql_conn.Open(); sql_comm.ExecuteNonQuery(); sql_conn.Close(); this .view_StudentTableAdapter.Fill(this .educationDataSet.View_Student); ) )

This handler executes an SQL UPDATE command that changes the current value of the active record.

10. Programming a click event on the button " Delete«.

The click event handler for the Delete button looks like this:

private void button3_Click(object sender, EventArgs e) ( string cmd_text = "DELETE FROM Student" ; int index; string num_book; index = dataGridView1.CurrentRow.Index; num_book = Convert.ToString(dataGridView1.Value); cmd_text = "DELETE FROM Student WHERE .=""+ num_book + """ ; SqlConnection sql_conn = new SqlConnection(conn_string); SqlCommand sql_comm = new SqlCommand(cmd_text, sql_conn); sql_conn.Open(); sql_comm.ExecuteNonQuery(); sql_conn.Close(); this .view_StudentTableAdapter.Fill (this .educationDataSet.View_Student); )

In this handler, the SQL command for deleting a DELETE record is executed.

Related topics

  • Displaying a Microsoft Access Database Table

Each of us regularly encounters and uses various databases. When we choose an address Email, we are working with a database. Databases use search services, banks to store customer data, and so on.

But, despite the constant use of databases, even for many developers software systems there are many "blank spots" due to different interpretations of the same terms. We will give a brief definition of basic database terms before looking at the SQL language. So.

Database - a file or set of files for storing ordered data structures and their relationships. Very often, a database is called a management system - it is only a repository of information in a certain format and can work with various DBMS.

table - Let's imagine a folder that stores documents grouped according to a certain attribute, for example, a list of orders for the last month. This is the table in the computer. A separate table has its own unique name.

Data type - the kind of information allowed to be stored in a particular column or row. It can be numbers or text of a certain format.

Column and row- we've all worked with spreadsheets that also have rows and columns. Any relational database works with tables in the same way. Rows are sometimes called records.

primary key- each table row can have one or more columns to uniquely identify it. Without a primary key, it is very difficult to update, modify, and delete the desired rows.

What is SQL?

SQL(English - structured query language) was developed only for working with databases and is currently the standard for all popular DBMS. The syntax of the language consists of a small number of operators and is easy to learn. But, despite the external simplicity, it allows the creation of sql queries for complex operations with a database of any size.

Since 1992 there has been a generally accepted standard called ANSI SQL. It defines the basic syntax and functions of operators and is supported by all DBMS market leaders such as ORACLE It is impossible to cover all the possibilities of the language in one small article, so we will briefly consider only basic SQL queries. Examples clearly show the simplicity and possibilities of the language:

  • creating databases and tables;
  • data sampling;
  • adding records;
  • modification and deletion of information.

SQL Data Types

All columns in a database table store the same type of data. Data types in SQL are the same as in other programming languages.

Creating tables and databases

There are two ways to create new databases, tables and other queries in SQL:

  • through the DBMS console
  • Using the interactive administration tools included with the database server.

A new database is created by the operator CREATE DATABASE<наименование базы данных>; . As you can see, the syntax is simple and concise.

We create tables inside the database using the CREATE TABLE statement with the following parameters:

  • table name
  • column names and data types

As an example, let's create a Commodity table with the following columns:

We create a table:

CREATE TABLE Commodity

(commodity_id CHAR(15) NOT NULL,

vendor_id CHAR(15) NOT NULL,

commodity_name CHAR(254) NULL,

commodity_price DECIMAL(8,2) NULL,

commodity_desc VARCHAR(1000) NULL);

The table has five columns. After the name comes the data type, the columns are separated by commas. The value of a column can be empty (NULL) or must be filled (NOT NULL), and this is determined when the table is created.

Selecting data from a table

The data selection operator is the most commonly used SQL query. To get information, you need to specify what we want to select from such a table. First a simple example:

SELECT commodity_name FROM Commodity

After the SELECT statement, we specify the name of the column for obtaining information, and FROM defines the table.

The result of the query execution will be all table rows with Commodity_name values ​​in the order in which they were entered into the database, i.e. without any sorting. An additional ORDER BY clause is used to order the result.

To query on multiple fields, list them separated by commas, as in the following example:

SELECT commodity_id, commodity_name, commodity_price FROM Commodity

It is possible to get the value of all columns of a row as a query result. For this, the "*" sign is used:

SELECT * FROM Commodity

  • Additionally SELECT supports:
  • Sorting data (ORDER BY statement)
  • Select according to conditions (WHERE)
  • Grouping term (GROUP BY)

Adding a line

To add a row to a table, SQL queries with the INSERT statement are used. Adding can be done in three ways:

  • add a new whole line;
  • part of a string;
  • query results.

To add a complete row, you must specify the table name and the values ​​of the columns (fields) of the new row. Here's an example:

INSERT INTO Commodity VALUES("106 ", "50", "Coca-Cola", "1.68", "No Alcohol ,)

The example adds a new product to the table. Values ​​are specified after VALUES for each column. If there is no corresponding value for the column, then NULL must be specified. The columns are populated with values ​​in the order specified when the table was created.

If you add only part of a row, you must explicitly specify the names of the columns, as in the example:

INSERT INTO Commodity (commodity_id, vendor_id, commodity_name)

VALUES("106 ", '50", "Coca Cola",)

We entered only the identifiers of the product, the supplier and its name, and left the rest of the fields blank.

Adding query results

INSERT is primarily used to add rows, but can also be used to add the results of a SELECT statement.

Change data

To change information in the fields of a database table, you must use the UPDATE statement. The operator can be used in two ways:

  • All rows in the table are updated.
  • Only for a certain line.

UPDATE consists of three main elements:

  • the table in which it is necessary to make changes;
  • field names and their new values;
  • conditions for selecting rows to change.

Consider an example. Let's say the price of a product with ID=106 has changed, so this row needs to be updated. We write the following operator:

UPDATE Commodity SET commodity_price = "3.2" WHERE commodity_id = "106"

We specified the name of the table, in our case Commodity, where the update will be performed, then after SET - the new value of the column and found the desired record by specifying the desired ID value in WHERE.

To change multiple columns, specify multiple column-value pairs separated by commas after the SET statement. Let's look at an example in which the name and price of the product is updated:

UPDATE Commodity SET commodity_name='Fanta', commodity_price = "3.2" WHERE commodity_id = "106"

To delete information in a column, you can set it to NULL if the table structure allows it. It must be remembered that NULL is exactly "no" value, and not zero in the form of text or a number. Remove product description:

UPDATE Commodity SET commodity_desc = NULL WHERE commodity_id = "106"

Removing rows

SQL queries to delete rows in a table are executed with the DELETE statement. There are two use cases:

  • certain rows in the table are deleted;
  • all rows in the table are deleted.

An example of deleting one row from a table:

DELETE FROM Commodity WHERE commodity_id = "106"

After DELETE FROM we specify the name of the table in which rows will be deleted. The WHERE clause contains a condition by which rows will be selected for deletion. In the example, we are deleting the product line with ID=106. Specifying WHERE is very important. omitting this statement will delete all rows in the table. This also applies to changing the value of fields.

The DELETE statement does not specify column names or metacharacters. It completely removes rows, but it cannot remove a single column.

Using SQL in Microsoft Access

Typically used interactively to create tables, databases, to manipulate, modify, analyze data in a database, and to implement queries SQL Access through a convenient interactive query designer (Query Designer), using which you can build and immediately execute SQL statements of any complexity.

The server access mode is also supported, in which the Access DBMS can be used as a generator of SQL queries to any ODBC data source. This capability allows Access applications to interact with any format.

SQL Extensions

Since SQL queries do not have all the features of procedural programming languages, such as loops, branches, etc., DBMS vendors develop their own version of SQL with advanced features. First of all, this is support for stored procedures and standard operators of procedural languages.

The most common dialects of the language:

  • Oracle Database - PL/SQL
  • Interbase, Firebird - PSQL
  • Microsoft SQL Server - Transact-SQL
  • PostgreSQL - PL/pgSQL.

SQL to the web

The MySQL DBMS is distributed under the GNU General Public License. There is a commercial license with the ability to develop custom modules. As an integral part, it is included in the most popular assemblies of Internet servers, such as XAMPP, WAMP and LAMP, and is the most popular DBMS for developing applications on the Internet.

It was developed by Sun Microsystems and is currently maintained by Oracle Corporation. Supports databases up to 64 terabytes, SQL:2003 syntax standard, replication of databases and cloud services.

SQL Server Management Studio provides a complete tool for creating all types of queries. With it, you can create, save, load and edit queries. In addition, you can work on queries without connecting to any server. This tool also provides the ability to develop queries for different projects.

You can work with queries through both the Query Editor and Solution Explorer. This article covers both of these tools. In addition to these two components of SQL Server Management Studio, we will look at debugging SQL code using the built-in debugger.

Query editor

To open the Query Editor panel Query Editor, on the SQL Server Management Studio toolbar, click the New Query button. This panel can be extended to display buttons for creating all possible queries, not just Database Engine queries. By default, a new Database Engine query is created, but you can also create MDX, XMLA, and other queries by clicking the corresponding button on the toolbar.

The status bar at the bottom of the Query Editor panel indicates the status of the editor's connection to the server. If you are not automatically connected to the server, when you launch the Query Editor, you will be presented with the Connect to Server dialog box, where you can select the server to connect to and the authentication mode.

Editing queries offline provides more flexibility than when you are connected to a server. You do not need to be connected to a server to edit queries, and the query editor window can be disconnected from one server (using the menu command Query --> Connection --> Disconnect) and connected to another without opening another editor window. To choose offline mode editing, in the dialog box for connecting to the server that opens when you launch the editor for a particular type of query, just click the Cancel button.

You can use the Query Editor to perform the following tasks:

    creating and executing Transact-SQL statements;

    saving generated Transact-SQL statements to a file;

    creating and analyzing execution plans for common queries;

    graphical illustration of the execution plan of the selected query.

The query editor contains a built-in text editor and a toolbar with a set of buttons for different actions. The main window of the Query Editor is divided horizontally into a Query Panel (top) and a Results Panel (bottom). The Transact-SQL statements (that is, queries) to be executed are entered in the top pane, and the results of the system processing those queries are displayed in the bottom pane. The figure below shows an example of entering a query in the query editor and the results of executing this query:

The first USE query statement specifies to use the SampleDb database as the current database. The second statement, SELECT, retrieves all the rows in the Employee table. To run this query and display the results, on the Query Editor toolbar, click the Execute button or press F5 .

You can open multiple Query Editor windows, i.e. make multiple connections to one or more instances of the Database Engine. A new connection is created by clicking the New Query button on the SQL Server Management Studio toolbar.

The status bar at the bottom of the Query Editor window displays the following information related to the execution of query statements:

    the status of the current operation (for example, "Request completed successfully");

    database server name;

    current user name and server process ID;

    the name of the current database;

    the time taken to complete the last request;

    the number of lines found.

One of the main advantages of SQL Server Management Studio is its ease of use, which also applies to the Query Editor. The Query Editor provides many features that make it easier to code Transact-SQL statements. In particular, it uses syntax highlighting to improve the readability of Transact-SQL statements. All reserved words are shown in blue, variables in black, strings in red, and comments in green.

In addition, the Query Editor has context-sensitive help called Dynamic Help, through which you can get information about a specific instruction. If you don't know the syntax of a statement, select it in the editor and then press the F1 key. You can also highlight the parameters of various Transact-SQL statements to get help on them from Books Online.

SQL Management Studio supports SQL Intellisense, which is a type of autocomplete tool. In other words, this module suggests the most likely completion of partially entered Transact-SQL statement elements.

The Object Explorer can also help with query editing. For example, if you want to know how to create a CREATE TABLE statement for the Employee table, right-click on that table in Object Explorer and the resulting context menu select Script Table As --> CREATE to --> New Query Editor Window. The Query Editor window containing the CREATE TABLE statement thus created is shown in the figure below. This capability also applies to other objects such as stored procedures and functions.

The Object Browser is very useful for graphically displaying the execution plan for a particular query. A query execution plan is an execution option chosen by the query optimizer among several possible options for executing a particular query. Enter the required query in the top panel of the editor, select a sequence of commands from the menu Query --> Display Estimated Execution Plan (Query --> Show Estimated Execution Plan) and the execution plan for this query will be displayed in the bottom panel of the editor window.

Solution Explorer

Editing queries in SQL Server Management Studio is based on the solutions method. If you create an empty query using the New Query button, it will be based on an empty solution. This can be seen by running the command sequence from the View --> Solution Explorer menu immediately after opening an empty query.

A decision can be related to none, one or more projects. An empty solution, not associated with any project. To associate a project with a solution, close the empty solution, Solution Explorer, and Query Editor, and create a new project by running the command sequence from the File --> New --> Project menu. In the New Project window that opens, select the SQL Server Scripts option in the middle pane. A project is a way of organizing files in a specific location. You can give the project a name and choose a location for its location on the disk. When you create a new project, a new solution is automatically launched. You can add a project to an existing solution using Solution Explorer.

For each created project, the Solution Explorer displays the Connections (Connections), Queries (Requests) and Miscellaneous (Miscellaneous) folders. To open a new Query Editor window for a given project, right-click its Queries folder and select New Query from the context menu.

Debugging SQL Server

SQL Server, starting with SQL Server 2008, has a built-in code debugger. To start a debugging session, select the following command sequence Debug --> Start Debugging from the main menu of SQL Server Management Studio. We will look at the operation of the debugger using an example using a command package. A batch is a logical sequence of SQL statements and procedural extensions that is sent to the Database Engine to execute all of the statements it contains.

The figure below shows a package that counts the number of employees working on a p1 project. If this number is 4 or more, then a corresponding message is displayed. Otherwise, the names and surnames of employees are displayed.

To stop the execution of a package at a specific instruction, you can set breakpoints, as shown in the figure. To do this, click to the left of the line on which you want to stop. When you start debugging, execution stops at the first line of code, which is marked with a yellow arrow. To continue execution and debugging, execute the menu command Debug --> Continue (Debugging --> Continue). Execution of the package instructions will continue to the first breakpoint, and the yellow arrow will stop at that point.

Information related to the debug process is displayed in two panes at the bottom of the Query Editor window. Information about different types debugging information is grouped in these panels on several tabs. The left panel contains the tab Autos (Automatic), Locals (Local) and up to five tabs Watch (Visible). The right pane contains the Call Stack, Threads, Breakpoints, Command Window, Immediate Window, and Output tabs. The Locals tab shows variable values, the Call Stack tab shows call stack values, and the Breakpoints tab shows information about breakpoints.

To stop the debugging process, execute the sequence of commands from the main menu Debug --> Stop Debugging or press the blue button on the debugger toolbar.

In SQL Server 2012, the built-in debugger in SQL Server Management Studio has been enhanced with several new features. Now you can perform a number of the following operations in it:

    Specify a breakpoint condition. Breakpoint condition is an SQL expression whose evaluated value determines whether the execution of the code will be stopped at a given point or not. To specify a breakpoint condition, right-click the red icon for the desired breakpoint and select Condition from the context menu. The Breakpoint Condition dialog box opens, in which you need to enter the necessary logical expression. In addition, if you want to stop execution if the expression is true, then you should set the Is True switch. If the execution needs to be stopped if the expression has changed, then you need to set the switch When Changed (Changed).

    Specify the number of hits to the breakpoint. The number of hits is the condition for stopping execution at a given point, based on the number of times that breakpoint has been hit during execution. When the specified number of iterations and any other condition specified for the given breakpoint is reached, the debugger performs the specified action. The break condition based on the number of hits can be one of the following:

    1. unconditional (default action) (Break always);

      if the number of hits is equal to the specified value (Break when the his count equals a specified value);

      if the number of hits is a multiple of the specified value (Break when the hit count equals a multiple of a specified value);

      if the number of hits is equal to or greater than the specified value (Break when the his count is greater or equal to a specified value).

    To set the number of hits during debugging, right-click the desired breakpoint icon on the Breakpoints tab, select Hit Count from the context menu, then select one of the conditions in the Breakpoint Hit Count dialog box that opens. from the list above. For options that require a value, enter it in the text box to the right of the conditions drop-down list. To save the specified conditions, click the OK button.

    Specify a breakpoint filter. The breakpoint filter restricts breakpoint operation to only specified computers, processes, or threads. To set a breakpoint filter, right-click the desired breakpoint and select Filter from the context menu. Then, in the Breakpoint Filters dialog box that opens, specify the resources that you want to limit the execution of this breakpoint to. To save the specified conditions, click OK.

    Specify an action at a breakpoint. The When Hit condition specifies the action to be taken when the package execution hits the given breakpoint. By default, when both the hit count condition and the stop condition are satisfied, then execution is aborted. Alternatively, you can display a pre-specified message.

    To specify what to do when a breakpoint is hit, right-click the red icon for the desired breakpoint and select When Hit from the context menu. In the When Breakpoint is Hit dialog box that opens, select the desired action. To save the specified conditions, click the OK button.

    Use the Quick Watch window. In the QuickWatch window, you can view the value of a Transact-SQL expression, and then save that expression in the Watch Values ​​window. To open the Quick Watch window, select Quick Watch from the Debug menu. The expression in this window can either be selected from the drop-down list Expression (Expression), or enter it into this field.

    Use the Quick Info tooltip. When you hover over a code ID, the Quick Info tool ( Brief information) displays its ad in a popup window.

Queries in Access are the main tool for selecting, updating and processing data in database tables. Access, in accordance with the concept of relational databases, uses a structured language to execute queries. SQL queries(Structured Query Language). With the help of SQL statements, any query in Access is implemented.

The main type of request is a select request. The result of this query is a new table that exists until the query is closed. Records are formed by combining the records of the tables on which the query is built. The method of combining table records is specified when defining their relationship in the data schema or when creating a query. The selection conditions formulated in the query allow you to filter the records that make up the result of joining tables.

Several types of queries can be created in Access:

  • sample request- selects data from one table or query or several related tables and other queries. The result is a table that exists until the query is closed. The formation of the results table records is carried out in accordance with the specified selection conditions and when using several tables by combining their records;
  • query to create a table- selects data from related tables and other queries, but, unlike a select query, saves the result in a new permanent table;
  • requests to update, add, delete- are action requests, as a result of which the data in the tables is changed.

Queries in Access in design mode contain a data schema that displays the tables used, and a query form in which the structure of the query table and conditions for selecting records are constructed (Fig. 4.1).

Using a query, you can perform the following types of data processing:

  • include user-selected table fields in the query table;
  • perform calculations in each of the received records;
  • select records that meet the selection criteria;
  • form a new virtual table based on the union of records of related tables;
  • group records that have the same values ​​in one or more fields, simultaneously perform statistical functions on other fields of the group and include one record for each group in the result;
  • create a new database table using data from existing tables;
  • update fields in the selected subset of records;
  • delete the selected subset of records from the database table;
  • add the selected subset of records to another table.

Queries in Access serve as record sources for other queries, forms, reports. Using a query, you can collect complete information to form a certain subject area document from several tables, then use it to create a form - an electronic representation of this document. If a form or report is created by the wizard based on several interrelated tables, then a query is automatically generated for them as a record source.
For fixing, watch the video tutorial.

SQL or Structured Query Language (structured query language) is designed to manage data in a relational database system (RDBMS). This article will cover commonly used SQL commands that every programmer should be familiar with. This material is ideal for those who want to brush up on their knowledge of SQL before a job interview. To do this, analyze the examples given in the article and remember that you went through databases in pairs.

Note that some database systems require a semicolon at the end of each statement. The semicolon is the standard pointer to the end of each statement in SQL. The examples use MySQL, so the semicolon is required.

Sample Database Setup

Create a database to show how the commands work. To work, you will need to download two files: DLL.sql and InsertStatements.sql . After that, open a terminal and log into the MySQL console with the following command (the article assumes that MySQL is already installed on the system):

MySQL -u root -p

Then enter the password.

Run the following command. Let's name the database "university":

CREATE DATABASE university; US university; SOURCE ; SOURCE

Database Commands

1. View available databases

SHOW DATABASES;

2. Create a new database

CREATE DATABASE;

3. Selecting a database to use

USE ;

4. Import SQL commands from .sql file

SOURCE ;

5. Deleting the database

DROP DATABASE ;

Working with tables

6. View tables available in the database

SHOW TABLES;

7. Create a new table

CREATE TABLE ( , , PRIMARY KEY ( ), FOREIGN KEY ( ) REFERENCES ());

Integrity Constraints When Using CREATE TABLE

You may need to create restrictions on certain columns in a table. When creating a table, you can set the following restrictions:

  • table cell cannot be NULL;
  • primary key - PRIMARY KEY (col_name1, col_name2, ...) ;
  • foreign key - FOREIGN KEY (col_namex1, …, col_namexn) REFERENCES table_name(col_namex1, …, col_namexn) .

You can specify more than one primary key. In this case, you get a composite primary key.

Example

Create an "instructor" table:

CREATE TABLE instructor (ID CHAR(5), name VARCHAR(20) NOT NULL, dept_name VARCHAR(20), salary NUMERIC(8,2), PRIMARY KEY (ID), FOREIGN KEY (dept_name) REFERENCES department(dept_name));

8. Information about the table

You can view various information (value type, key or not) about the columns of a table with the following command:

DESCRIBE ;

9. Adding data to the table

INSERT INTO (, , , …) VALUES ( , , , …);

When you add data to each column of a table, you do not need to specify column names.

INSERT INTO VALUES ( , , , …);

10. Update table data

UPDATE SET = , = , ... WHERE ;

11. Deleting all data from the table

DELETE FROM ;

12. Deleting a table

DROP TABLE ;

Commands for creating queries

13. SELECT

SELECT is used to get data from a specific table:

SELECT , , … FROM ;

The following command can display all the data from the table:

SELECT * FROM ;

14. SELECT DISTINCT

Table columns can contain duplicate data. Use SELECT DISTINCT to get only non-duplicate data.

SELECT DISTINCT , , … FROM ;

15. WHERE

You can use the WHERE keyword in SELECT to specify conditions in a query:

SELECT , , … FROM WHERE ;

You can specify the following conditions in a request:

  • text comparison;
  • comparison of numerical values;
  • logical operations AND (and), OR (or) and NOT (negation).

Example

Try the following commands. Pay attention to the conditions specified in WHERE:

SELECT * FROM course WHERE dept_name='Comp. Sci.'; SELECT * FROM course WHERE credits>3; SELECT * FROM course WHERE dept_name="Comp. Sci." AND credits>3;

16. GROUP BY

The GROUP BY clause is often used with aggregate functions, such as COUNT , MAX , MIN , SUM , and AVG , to group output values.

SELECT , , … FROM GROUP BY ;

Example

Let's display the number of courses for each faculty:

SELECT COUNT(course_id), dept_name FROM course GROUP BY dept_name;

17. HAVING

The HAVING keyword was added to SQL because WHERE cannot be used with aggregate functions.

SELECT , , ... FROM GROUP BY HAVING

Example

Let's display a list of faculties that have more than one course:

SELECT COUNT(course_id), dept_name FROM course GROUP BY dept_name HAVING COUNT(course_id)>1;

18. ORDER BY

ORDER BY is used to sort query results in ascending or descending order. ORDER BY sorts in ascending order unless ASC or DESC is specified.

SELECT , , … FROM ORDER BY , , …ASC|DESC;

Example

Let's display a list of courses in ascending and descending order of the number of credits:

SELECT * FROM course ORDER BY credits; SELECT * FROM course ORDER BY credits DESC;

19. BETWEEN

BETWEEN is used to select data values ​​from a certain range. Numeric and text values, as well as dates, can be used.

SELECT , , … FROM WHERE BETWEEN AND ;

Example

Let's display a list of instructors whose salary is more than 50,000 but less than 100,000:

SELECT * FROM instructor WHERE salary BETWEEN 50000 AND 100000;

20.LIKE

The LIKE operator is used in WHERE to specify a pattern to look for a similar value.

There are two free operators that are used in LIKE:

  • % (none, one or more characters);
  • _ (one character).
SELECT , , … FROM WHERE LIKE ;

Example

Let's display a list of courses whose names contain "to" , and a list of courses whose names start with "CS-":

SELECT * FROM course WHERE title LIKE '%to%'; SELECT * FROM course WHERE course_id LIKE "CS-___";

21. IN

With IN, you can specify multiple values ​​for the WHERE clause:

SELECT , , … FROM WHERE IN( , , …);

Example

Let's display the list of students from directions Comp. Sci., Physics and Elec. English:

SELECT * FROM student WHERE dept_name IN('Comp. Sci.', 'Physics', 'Elec. Eng.');

22. JOIN

JOIN is used to link two or more tables using common attributes within them. The image below shows different ways to join in SQL. Notice the difference between a left outer join and a right outer join:

SELECT , , … FROM JOIN ON = ;

Example 1

Here is a list of all courses and the corresponding department information:

SELECT * FROM course JOIN department ON course.dept_name=department.dept_name;

Example 2

Here is a list of all required courses and details about them:

SELECT prereq.course_id, title, dept_name, credits, prereq_id FROM prereq LEFT OUTER JOIN course ON prereq.course_id=course.course_id;

Example 3

Let's display a list of all courses, regardless of whether they are required or not:

SELECT course.course_id, title, dept_name, credits, prereq_id FROM prereq RIGHT OUTER JOIN course ON prereq.course_id=course.course_id;

23 View

View is a virtual SQL table created as a result of executing an expression. It contains rows and columns and is very similar to a normal SQL table. View always shows the latest information from the database.

Creation

CREATE VIEW AS SELECT , , … FROM WHERE ;

Removal

DROP VIEW ;

Example

Let's create a view consisting of courses with 3 credits:

24. Aggregate functions

These functions are used to obtain an aggregate result related to the data in question. The following are commonly used aggregate functions:

  • COUNT (col_name) - returns the number of rows;
  • SUM (col_name) - returns the sum of the values ​​in the given column;
  • AVG (col_name) - returns the average value of the given column;
  • MIN (col_name) - returns the smallest value of the given column;
  • MAX(col_name) - Returns the largest value of the given column.

25. Nested subqueries

Nested subqueries are SQL queries that include SELECT , FROM , and WHERE statements nested within another query.

Example

Let's find the courses that were taught in the fall of 2009 and in the spring of 2010:

SELECT DISTINCT course_id FROM section WHERE semester = 'Fall' AND year= 2009 AND course_id IN (SELECT course_id FROM section WHERE semester = 'Spring' AND year= 2010);

© 2022 hecc.ru - Computer technology news