sql中变量用法_SQL变量:基础和用法

sql中变量用法

In this article, we will learn the notions and usage details of the SQL variable. In SQL Server, local variables are used to store data during the batch execution period. The local variables can be created for different data types and can also be assigned values. Additionally, variable assigned values can be changed during the execution period. The life cycle of the variable starts from the point where it is declared and has to end at the end of the batch. On the other hand, If a variable is being used in a stored procedure, the scope of the variable is limited to the current stored procedure. In the next sections, we will reinforce this theoretical information with various examples

在本文中,我们将学习SQL变量的概念和用法细节。 在SQL Server中,局部变量用于在批处理执行期间存储数据。 可以为不同的数据类型创建局部变量,也可以为其分配值。 此外,可以在执行期间更改变量分配的值。 变量的生命周期从声明它的点开始,并且必须在批处理结束时结束。 另一方面,如果在存储过程中使用了变量,则该变量的范围仅限于当前存储过程。 在下一部分中,我们将通过各种示例来加强这一理论信息

Note: In this article examples, the sample AdventureWorks database is used.

注意:在本文示例中,将使用示例AdventureWorks数据库。

SQL变量声明 (SQL Variable declaration)

The following syntax defines how to declare a variable:

以下语法定义了如何声明变量:

DECLARE { @LOCAL_VARIABLE data_type [ = value ] }

Now, let’s interpret the above syntax.

现在,让我们解释以上语法。

Firstly, if we want to use a variable in SQL Server, we have to declare it. The DECLARE statement is used to declare a variable in SQL Server. In the second step, we have to specify the name of the variable. Local variable names have to start with an at (@) sign because this rule is a syntax necessity. Finally, we defined the data type of the variable. The value argument which is indicated in the syntax is an optional parameter that helps to assign an initial value to a variable during the declaration. On the other hand, we can assign or replace the value of the variable on the next steps of the batch. If we don’t make any initial value assigned to a variable, it is initialized as NULL.

首先,如果要在SQL Server中使用变量,则必须对其进行声明。 DECLARE语句用于在SQL Server中声明变量。 在第二步中,我们必须指定变量的名称。 局部变量名称必须以at(@)符号开头,因为此规则是语法上的必要性。 最后,我们定义了变量的数据类型。 语法中指示的value参数是一个可选参数,有助于在声明期间为变量分配初始值。 另一方面,我们可以在批处理的后续步骤中分配或替换变量的值。 如果我们不给变量赋任何初始值,则将其初始化为NULL。

The following example wi

你可能感兴趣的:(java,sql,python,数据库,mysql)