In this article, we will explore computed columns in SQL Server and their configurations.
在本文中,我们将探讨SQL Server中的计算列及其配置。
介绍 (Introduction)
Suppose you have an [Orders] table and it holds the information about orders placed by the customers for an online shopping portal.
假设您有一个[Orders]表,它包含有关客户为在线购物门户下的订单的信息。
You have different tax slabs for the different products, and you require a column in your table that has the amount for each order after adding required taxes. In this case, you can utilize computed columns in SQL Server.
对于不同的产品,您有不同的税率标准,并且您需要在表中的一列中添加每笔订单的税额,然后加上所需的税额。 在这种情况下,您可以利用SQL Server中的计算列。
Similarly, in another example of [Employee] table, we have a DOB for each employee. We need a computed column to show [Age] of the employee.
同样,在[Employee]表的另一个示例中,我们为每个员工都有一个DOB。 我们需要一个计算列来显示员工的[年龄]。
A computed column in SQL Server is a virtual column that computes its values from an expression. We can use a constant value, function, value derived from other columns, non-computed column name, or their combinations.
SQL Server中的计算列是一个虚拟列,它根据表达式计算其值。 我们可以使用常量值,函数,从其他列派生的值,未计算的列名或其组合。
SQL Server does not store these virtual columns physically, so it does not require any storage. We can store these columns physically as well using PERSISTED property if required. If we mark a computed column as persisted, we can define constraints such as Check, Not NULL, or Foreign key. It also allows you to define an index for the persisted computed column.
SQL Server不会物理存储这些虚拟列,因此不需要任何存储。 如果需要,我们还可以使用PERSISTED属性来物理存储这些列。 如果将计算列标记为持久列,则可以定义约束,例如Check,Not NULL或Foreign key。 它还允许您为持久化的计算列定义索引。
Let’s create a new table using the SSMS table designer wizard. Expand Databases -> right-click on Tables and navigate to New -> Table:
让我们使用SSMS表设计器向导创建一个新表。 展开数据库 ->右键单击表格 ,然后导航到新建 -> 表格 :
In the above image, the table shows multiple columns and their data types. We have defined a primary key and identity column on the [EmpID] column.
在上图中,该表显示了多个列及其数据类型。 我们在[EmpID]列上定义了一个主键和标识列。
Add a new column [Age]. In this column, do not select the data type. SQL Server automatically assigns an appropriate data type depending upon the columns for the computed column in SQL Server value.
添加一个新列[年龄]。 在此列中,不要选择数据类型。 SQL Server会根据SQL Server值中计算列的列自动分配适当的数据类型。
In the Computed Column Specification, specify the formula for computed column value. In my example [Age] column, we use the DATEDIFF() function to calculate the employee age.
在“ 计算列规格”中 ,指定计算列值的公式。 在我的示例[Age]列中,我们使用DATEDIFF()函数来计算员工年龄。
Formula: datediff(year,DOB,getdate())
公式: datediff(year,DOB,getdat