📜  into in sql (1)

📅  最后修改于: 2023-12-03 14:42:08.526000             🧑  作者: Mango

Introduction to 'INTO' in SQL

Overview

In SQL, the 'INTO' clause is used to store the query result into variables or tables. It is commonly used in SELECT statements to retrieve data and save it for further processing or analysis.

Syntax

The basic syntax of the 'INTO' clause is as follows:

SELECT column1, column2, ...
INTO variable1, variable2, ...
FROM table_name
WHERE condition;

Here, table_name is the name of the table from which you want to retrieve the data, and condition is an optional condition that specifies which rows to select. column1, column2, ... refers to the columns you want to select from the table.

The 'INTO' clause allows you to store the selected data into variable1, variable2, ... or a new table.

Usage Examples
1. Storing Data into Variables
DECLARE @name VARCHAR(50);
DECLARE @age INT;

SELECT first_name, age
INTO @name, @age
FROM users
WHERE user_id = 1;

In this example, the first name and age of the user with user_id = 1 are selected from the 'users' table and stored into the variables @name and @age, respectively.

2. Creating a New Table from Query Result
SELECT product_name, price
INTO new_products
FROM products
WHERE price > 100;

This example creates a new table called 'new_products' by selecting the product name and price from the 'products' table where the price is greater than 100.

Conclusion

The 'INTO' clause in SQL provides a way to store query results into variables or create new tables. It is a useful feature for managing and manipulating data within a database.