Internet. Computer. Help. Adviсe. Repair

Query to populate a sql table. How to work with the database

Before you can create an SQL table, you need to define the database model. Design an ER diagram in which to define entities, attributes and relationships.

Basic Concepts

Entities are objects or facts about which information must be stored. For example, an employee of a company or projects implemented by the company. Attributes are components that describe or qualify an entity. For example, the attribute of the “employee” entity is salary, and the attribute of the “project” entity is the estimated cost. Connections are associations between two elements. It can be bidirectional. There is also a recursive connection, that is, the connection of an entity with itself.

It is also necessary to determine the keys and conditions under which the integrity of the database will be maintained. What does it mean? In other words, restrictions that will help keep databases in a correct and consistent form.

Transition from ER diagram to tabular model

Rules for transition to a tabular model:

  1. Convert all entities to tables.
  2. Convert all attributes to columns, that is, each entity attribute must appear in the table column name.
  3. Convert unique identifiers into primary keys.
  4. Convert all relationships to foreign keys.
  5. Create the SQL table.

Creating a database

First you need to start the MySQL server. To launch it, go to the Start menu, then Programs, then MySQL and MySQL Server, select MySQL-Command-Line-Client.

To create a database, use the Create Database command. This function has the following format:

CREATE DATABASE database_name.

The restrictions on the name of the database are as follows:

  • length is up to 64 characters and can include letters, numbers, "" and "" symbols;
  • the name can start with a number, but it must contain letters.

You need to remember the general rule: any request or command ends with a delimiter. In SQL, it is common to use a semicolon as a delimiter.

The server needs to indicate which database it will need to work with. There is a USE statement for this. This operator has a simple syntax: USE n database_name.

Creating a SQL Table

So, the model is designed, the database is created, and the server is told exactly how to work with it. Now you can start creating SQL tables. There is Data Definition Language (DDL). It is used to create MS SQL table, as well as to define objects and work with their structure. DDL includes a set of commands.

SQL Server table creation

Using just one DDL command, you can create various database objects by varying its parameters. The Create Table command is used. The tt format looks like this:

CREATE TADLE table_name,(column_name1 Name _column2 datatype [column_constraint],[table_constraints]).

The syntax of this command should be described in more detail:

  • The table name must be up to 30 characters long and begin with a letter. Only alphabetic characters, letters, and the symbols "_", "$" and "#" are allowed. The use of Cyrillic alphabet is allowed. It is important to note that table names should not be the same as other object names or database server reserved words such as Column, Table, Index, etc.
  • You must specify a data type for each column. There is a standard set used by most. For example, Char, Varchar, Number, Date, Null type, etc.

  • The Default parameter allows you to set a default value. This ensures that there are no null values ​​in the table. What does it mean? The default value can be a symbol, an expression, a function. It is important to remember that this default data type must match the column's input data type.
  • Constraints on each column are used to enforce integrity conditions for data at the table level. There are other nuances. It is prohibited to delete a table if there are other tables dependent on it.

How to work with the database

Large projects often require the creation of multiple databases, each requiring many tables. Of course, it is impossible for users to retain all the information in their heads. To do this, it is possible to view the structure of databases and tables in them. There are several commands, namely:

  • SHOW DATABASES - shows all created SQL databases on the screen;
  • SHOW TABLES - displays a list of all tables for the current database that are selected by the USE command;
  • DESCRIBE table_name- shows a description of all table columns.
  • ALTER TABLE - allows you to change the table structure.

The last command allows:

  • add a column or constraint to a table;
  • change an existing column;
  • delete column or columns;
  • remove integrity constraints.

The syntax for this command is: ALTER TABLE table_name( | | | | [(ENABLE | DISABLE) CONSTANT constraint_name ] | }.

There are other commands:

  • RENAME - rename the table.
  • TRUNCATE TABLE - removes all rows from the table. This function may be needed when it is necessary to fill the table again, but there is no need to store previous data.

There are also situations when the structure of the database has changed and the table should be deleted. There is a DROP command for this. Of course, you first need to select the database from which you want to delete the table, if it is different from the current one.

The command syntax is quite simple: DROP TABLE Name_tables.

In SQL Access, tables are created and modified using the same commands listed above.

Using CREATE TABLE you can create an empty table and then fill it with data. But that is not all. You can also directly create a table from another table. Like this? That is, it is possible to define a table and fill it with data from another table. There is a special keyword AS for this.

The syntax is very simple:

  • CREATE TABLE Name_tables[(column_definition)] AS subquery;
  • column_definition - column names, integrity rules for newly created table columns, and default values;
  • subquery - returns the rows that need to be added to the new table.

Thus, such a command creates a table with certain columns, inserts rows into it, which are returned in the query.

Temporary tables

Temporary tables are tables whose data is erased at the end of each session or earlier. They are used to record intermediate values ​​or results. They can be used as worksheets. You can define temporary ones in any session, but you can use their data only in the current session. Creating temporary SQL tables is similar to regular tables, using the CREATE TABLE command. In order to show the system that the table is temporary, you need to use the GLOBAL TEMPORARY parameter.

The ON COMMIT clause sets the lifetime of data in such a table and can do the following:

  • DELETE ROWS - clear the temporary table (delete all session data) after each transaction completion. This is usually the default value.
  • PRESERVE ROWS - leave data for use in the next transaction. In addition, you can clear the table only after the session ends. But there are some peculiarities. If a transaction is rolled back (ROLLBACK), the table will be returned to its state at the end of the previous transaction.

The syntax for creating a temporary table can be represented as follows: CREATE TABLE Name_tables,(Namecolumn_1 datatype [column_constraint], Name _column2 datatype [column_constraint], [table_constraints]).

Question: Populating tables with sql queries


probably a hackneyed topic, but still... filling out tables using queries... having problems... help me figure out what’s wrong. I need to create a “Water Supply” database
using the queries attached in the file, I created tables..
I started filling them out, again using queries, and errors started appearing...
1st error:
I am writing a request to fill in general data for the tApartments table from the tBudinka table:

INSERT INTO tApartments([apartment#], [budinka_code]) SELECT * FROM tBudinkas
throws an error "The INSERT INTO statement contains an unknown field name #budinka. Check that the name was specified without errors and repeat the operation"
Did I miss something in the request? how to fix this error???

2nd mistake
I filled out the tTariff table by hand.. now I need the general data on the last tariff in this table to go to the tPayment_plan table..
A request for the latest tariff using the max function looks like this:
SELECT Installation_date, Tariff_1people, tariff_code FROM tTariff WHERE Installation_date = (SELECT MAX (Installation_date) FROM (tTariff));
it works as a separate query, but as I understand it, from this query the value for tariff_code should be copied to the toPayment_plan table, i.e. I create the following query:

INSERT INTO payment_plan (tariff_code) SELECT tariff_code FROM tTariff WHERE (SELECT tariff_code FROM tTariff WHERE Installation_date = (SELECT MAX (Installation_date) FROM (tTariff));)

but there’s also an error here (I haven’t figured out how to post pictures here, but I hope it will be clear):

what am I doing wrong??? please tell me... otherwise it’s hard for me to figure out my mistakes like a teapot

Attached to the message is a file ( in.txt- 2Kb)

Answer: lisica198808,

In the first query, you most likely have a structure (number and types of columns) tApartments and tBudinki do not match. Instead of an asterisk, explicitly list in SELECT the names of those columns from the tBudinki table that you want to use in tApartments.

In the second query, you most likely have several columns in toPayment_Plan, some of which do not allow NULL values. You add a value to only one column (tariff_code), the rest are filled with either default values ​​(if defined) or NULL in the query you have. Hence the error.

Be sure to listen to sdku's advice.

Question: Problems with the counter when filling out the table


Good day
I'm doing a procedure to fill a table that has a counter field.
It gives an error even though I added SET IDENTITY_INSERT dbo.Clients ON
T-SQL
1 2 3 4 5 6 7 8 9 10 11 12 13 14 alter proc [ dbo].[ Add_Client] @fiok varchar (50 ) , @telk varchar (50 ) , @skidk char (3 ) as declare @kklient int set @kklient = (select max (Client_code) from dbo.Clients) + 1 SET IDENTITY_INSERT dbo.Clients ON insert dbo.Clients values ​​(@kklient, @fiok, @telk, @skidk) SET IDENTITY_INSERT dbo.Clients OFF select "Client added:"+ @fiok + "Tel:" + @telk + "Discount:" + @skidk

Error - The identity column value in table 'dbo.Clients' can only be specified explicitly when using a column list and when IDENTITY_INSERT is set to ON.

Answer:

Message from _JoNi_

I tried this, now when I run it it shows this
Sorry for the stupid questions, I just started learning sql)

Can you, after the name of the table you are inserting into, write the field names in parentheses separated by commas?!

Question: Filling a Word table with a bookmark with data from an Access query - looking for a solution


Hello, good people!

Somewhere on the Internet I found a working example of filling a Word table with data from Access using bookmarks. It works (Example.zip).
Unfortunately, I’m self-taught in Access and don’t know much...
No matter how I tried to implement the solution from a working example in my database (WORD.zip), I couldn’t do anything.
I insert elements from the example in the form of functions, as it is implemented in it, and turn to them - it curses in every way.
I insert parts of these functions into my code - again he swears!

What should be inserted not into the table, it is miraculously substituted in place of bookmarks (it works if you remove from the code everything that relates to filling out the table).

I have no more strength

Please, good people, correct my code so that everything works!
And if you also clearly explain why it didn’t work out for me, I will consider you to be the wisest and most responsive
Access2010

Thank you in advance!!!

P.S. In my database there are tables with Moscow streets, Last names, First names, Patronymics, Units of measurement (official abbreviations) - use whoever needs it

Answer: then there will be a stop after 2 lines (on the insert line)
--
I couldn't get this second option to work yesterday( corbis. point 2)
I got the first one (initial) right in an hour (about 10 mistakes)

Question: Error when filling the table with data


The NewCompany database has been created, the EmployeeSchema.Employee table has been created in it, the problem is that when filling the table programmatically, errors occur, given that the last column must be left empty.
I don't know how to fix it. Help me please.

Creating a table
USE NewCompany_Ezh;
GO

CREATE TABLE EmployeeSchema.Employee
EmpID int NOT NULL,
LName varchar(20) NOT NULL,
FName varchar(20) NOT NULL,
Title varchar(20) NULL,
BirthDate date NULL,
EmpDate date NULL,
Salary decimal(18, 2) NOT NULL,
DepID int NOT NULL,
OrgNode hierarchyid NULL,
GO

Filling
USE NewCompany_Ezh;
GO
DECLARE @child hierarchyid,
@manager hierarchyid = hierarchyid::GetRoot()

Root level - Director

(1, N"Ivanov", N"Ivan", N"Director", "1975-05-07", "2009-05-06", 30000.00, @manager)

Next level - Deputies

INSERT INTO EmployeeSchema.Employee VALUES
(2, N"Petrov", N"Petr", N"Deputy Director", "1969-10-07", "2005-07-07", 25000.00, @child)

INSERT INTO EmployeeSchema.Employee VALUES
(3, N"Sidorov", N"Sidor", N"Deputy Director", "1981-05-05", "2009-09-09", 25000.00, @child)

SELECT @child = @manager.GetDescendant(@child, NULL)

INSERT INTO EmployeeSchema.Employee VALUES
(4, N"Eremin", N"Erema", N"Deputy Director", "1986-11-01", "2009-10-10", 25000.00, @child)

Next level of hierarchy
SELECT @manager = OrgNode
FROM EmployeeSchema.Employee WHERE EmpID = 4
SELECT @child = @manager.GetDescendant(NULL, NULL)

INSERT INTO EmployeeSchema.Employee VALUES
(5, N"Alexandrov", N"Alexander", N"Assistant", "1979-01-01", "2008-01-01", 20000.00, @child)

SELECT @child = @manager.GetDescendant(@child, NULL)
INSERT INTO EmployeeSchema.Employee VALUES
(6, N"Andreev", N"Andrey", N"Assistant", "1985-04-12", "2008-01-01", 20000.00, @child)
GO

Answer:

Message from Margaret98

NewCompany database created

We are definitely talking about MySQL, not MS SQL

Question: Error #1062 when filling a table


Good afternoon.
Please help me solve the problem when filling out the table it gives the following error:
,
Primary key - specified.
It’s strange, if when filling out you start id_zanyt(pk) not with 1 but with 2, then it doesn’t give an error...

Answer: Everything has been decided!)) I need to delete the topic!

Question: Filling a table in a database from a field (TextBox) in a form


Hello, I was digging on the Internet about filling out a table from a TextBox in a form and came across an article

And I don’t quite understand why you need to prescribe this? if the form and table are in the same database, will this part of the code look different?
Dim z As New OleDb.OleDbConnection( "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:1Microsoft Office Access Application.mdb") "We establish a connection to the database. z.Open() "We open the connection.
and second

Dim t As New OleDb.OleDbCommand( "UPDATE [Table1] SET [Field1] = " "& " " & TextBox1.Text & " " WHERE [Code] = 1", z)
why do I need the z variable?

Question: Filling tables automatically


Hello
Tell me please
I have a table in sql. 3 columns (fields), the first one is automatically filled in
I want to fill in fields 2 and 3 using a request
so that field 2 is from 0 to 99 in increments of 3
3 field 3 to 102 in increments of 3
that is, get a large filled table at once
I don’t understand how to make a request
tried it
use database name;
insert into Runnums (field2, field3)
values ​​(0.3)
but this only fills one line
thanks in advance

Working with databases is directly related to changing tables and the data they contain. But before you begin, tables must be created. To automate this process, there is a special one - “CREATE TABLE”.

First thing!

Before understanding the process of creating tables using the MS SQL "CREATE TABLE" command, it is worth dwelling on what you need to know before using the function.

First of all, you need to come up with a name for the table - it must be unique in comparison with others in the database, and follow several rules. The name must begin with a letter (a-z), followed by any letters, numbers, or underscores, and the resulting phrase must not be a reserved word. The length of the table name should not exceed 18 characters.

Having decided on a name, you should develop a structure: come up with names for the columns, think about the data type used in them and which fields must be filled in. Here it is worth immediately defining the fields of foreign and primary keys, as well as possible restrictions on data values.

The remaining nuances of the table can be corrected quite easily, so at the stage of creating the table they may not be fully thought through.

Syntax

Having developed the structure of the table, you can proceed to its creation. This can be done quite simply by using the SQL function "CREATE TABLE". In it, the user is required to specify the previously invented table name and list of columns, indicating the type and name for each of them. The function syntax is as follows:

CREATE TABLE table_name
((column_name datatype …| table_constraint)
[,(column_name datatype …| table_constraint)]…)

The arguments used in the function construction mean the following:

  • table_name - table name
  • column_name - column name
  • datatype - the data type used in this field
  • DEFAULT is the default expression used in the column.

It is also possible to use two more function arguments:

  • column_constraint - column parameters
  • table_constraint - table parameters

In them, the user can specify the restrictions required for work or the conditions for filling out the table.

Features of creating tables

When writing a query with a function, sometimes it is necessary to set rules for filling in fields. To do this, you need to add special function attributes that define a particular set of conditions.

In order to determine whether a cell can contain an empty value, after specifying the name and type of the column, you should enter one of the keywords: NULL (there may be empty values) or NOT NULL (the field must be filled).

When creating a table, in most cases you need to unify each record to avoid having two identical ones. To do this, line numbering is most often used. And, in order not to require the user to know the last number in the table, in the "CREATE TABLE" function it is enough to indicate the primary key column by writing the keyword "Primary key" after the corresponding field. Most often, it is by the primary key that the tables are joined to each other.

To ensure concatenation with the Primary key, the foreign key property "FOREIGN KEY" is used. By specifying this property for a column, you can ensure that this field will contain a value that matches one of those in the primary key column of the same or another table. In this way, data consistency can be ensured.

To provide a check against a specified set or definition, you should use the CHECK attribute. It is written last in the list of function arguments and has a logical expression as a personal parameter. With its help, you can limit the list of possible values, for example, using only the letters “M” and “F” in the “Gender” table field.

In addition to those presented, the function has many more specific attributes, but they are used much less frequently in practice.

Examples

To fully understand the principle of operation of the function, it is worth considering in practice how CREATE TABLE (SQL) works. The example below creates the table shown in the figure:

CREATE TABLE Custom
(ID CHAR(10) NOT NULL Primary key,
Custom_name CHAR(20),
Custom_address CHAR(30),
Custom_city CHAR(20),
Custom_Country CHAR(20),
ArcDate CHAR(20))

As you can see, the parameter for the possible absence of a value in a cell (NULL) can be omitted, since it is used by default.

  • How can I combine SELECT statements so I can calculate percentages, successes and failures in SQL Server?
  • SQL: How to select only individual rows based on some property values
  • How to choose the product with the maximum price in each category?
LevelId Min Product 1 x 1 2 y 1 3 z 1 4 a 1

I need to duplicate the same data in the database by changing only the product ID from 1 2,3.... 40

LevelId Min Product 1 x 2 2 y 2 3 z 2 4 a 2

I could do something like

INSERT INTO dbo.Levels SELECT top 4 * fROM dbo.Levels but this will just copy the data. Is there a way I can copy the data and paste it, changing only the Product value?

You're most on your way - you need to take one more logical step:

INSERT INTO dbo.Levels (LevelID, Min, Product) SELECT LevelID, Min, 2 FROM dbo.Levels WHERE Product = 1

... will duplicate your rows with a different product ID.

Also note that WHERE Product = 1 will be more reliable than TOP 4 . Once you have more than four rows in the table, you cannot guarantee that TOP 4 will return the same four rows unless you also add an ORDER BY to select, however WHERE Product = ... will always return the same and will continue work even if you add an extra row with Product ID 1 (where you'll need to consider changing TOP 4 to TOP 5 etc if you add extra rows).

You can generate the product ID and then load it into:

< 40) INSERT INTO dbo.Levels(`min`, product) SELECT `min`, cte.n as product fROM dbo.Levels l cross join cte where l.productId = 1;

This assumes that LevelId is an identifier column that is automatically incremented on insertion. If not:

With cte as (select 2 as n union all select n + 1 from cte where n< 40) INSERT INTO dbo.Levels(levelid, `min`, product) SELECT l.levelid+(cte.n-1)*4, `min`, cte.n as product fROM dbo.Levels l cross join cte where l.productId = 1;

INSERT INTO dbo.Levels (LevelId, Min, Product) SELECT TOP 4 LevelId, Min, 2 FROM dbo.Levels

You can include expressions in the SELECT , either hardcoded values, or something like Product + 1 or something else.

I expect that you probably won't want to insert the LevelId, but leave it there to fit your pattern. If you don't want this just remove it from the INSERT and SELECT sections.

For example, you can use CROSS JOIN on a table of numbers.

WITH L0 AS(SELECT 1 AS C UNION ALL SELECT 1 AS O), -- 2 rows L1 AS(SELECT 1 AS C FROM L0 AS A CROSS JOIN L0 AS B), -- 4 rows Nums AS(SELECT ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) AS N FROM L1) SELECT lvl., lvl., num.[N] FROM dbo. lvl CROSS JOIN Nums num

This will be repeated 4 times.

Did you like the article? Share with your friends!
Was this article helpful?
Yes
No
Thanks for your feedback!
Something went wrong and your vote was not counted.
Thank you. Your message has been sent
Found an error in the text?
Select it, click Ctrl + Enter and we will fix everything!