SELECT INTO command in SQL Server

The article guides using SELECT INTO command in SQL Server with syntax and examples.

In SQL Server (Transact-SQL), the SELECT INTO command is used to create a table from an existing table by copying columns from the original table.

Remember that when creating a table in this way, the new table will also be filled with records from the old table (based on the SELECT statement).

Syntax SELECT INTO command

 SELECT bi eu_thuc 
INTO bang_moi
FROM bang
[WHERE dieu_k ien];

Variable name or variable value

bieu_thuc

Column or value you want to retrieve.

bang_moi

New table created with selected expressions and related definitions. (bang_moi is not currently available).

state

Table wants to get records from there. Must have at least 1 table in the FROM clause.

WHERE dieu_kien

Option. Conditions must satisfy for the selected record.

Note

When using the SELECT INTO command in SQL Server, bang_moi must never exist before. If so, the SELECT INTO command will fail.

Example SELECT INTO command

 SELECT nhanvien_id,  ho, ten 
INTO danhba
FROM nhanvien
WHERE nhanvie n_id <1000;

In this example, the SELECT INTO command will select the ID, surname and name of the employee in the table and copy these fields with the definition to a new list.

If there is a record in the table, the new list will also have the records returned from the SELECT statement.

If you want to rename the column in the new table instead of using the old name, you can set the alias ALIAS for the column in the SELECT INTO command.

 SELECT nhanvien_id AS da nhba_id, ho, ten 
INTO danhba
FROM nhanvien
WHERE nhanvien_id < 1000 ;

In the above example, we do not want the first column in the namba table to be nhanvien_id, so it is better to rename the first column to listba_id in the list. This is done by setting the alias for the nhanvien_id column as shown below.

 nhanvien_id AS danhba_id 

Previous article: SELECT TOP command in SQL Server

The following article: DELETE TOP command in SQL Server

4.5 ★ | 2 Vote