Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the data type of a computed column?

Tags:

When you CREATE TABLE using CASE expression to create a computed column, you do not explicitly define the data type of this column:

CREATE TABLE OrderDetail ( OrderID INT , ProductID INT , Qty INT , OrderDate DATETIME , ShipDate DATETIME , STATUS AS CASE        WHEN shipdate is NULL AND orderdate < DATEADD( dd, -7, GETDATE()) THEN 3         WHEN shipdate is NOT NULL THEN 2         ELSE 1    end  ) GO 

How SQL Server decides the data type of this column?

like image 872
jrara Avatar asked Sep 23 '12 17:09

jrara


People also ask

What is a computed column?

A computed column is a virtual column that is not physically stored in the table, unless the column is marked PERSISTED. A computed column expression can use data from other columns to calculate a value for the column to which it belongs.

How do you use a computed column in SQL?

Go to your database, right click on tables, select “New Table” option. Create all columns that you require and to mark any column as computed, select that column and go to column Properties window and write your formula for computed column.

How do I find the computed column in SQL Server?

Get a list of computed columns in a SQL Server database. We can use the system function sys. computed_columns and join it with the sys. objects to get a list of available computed columns, their data type, and the column definition (formula).

What is database column type?

The data type of a column defines what value the column can hold: integer, character, money, date and time, binary, and so on.


1 Answers

In addition, if you want to force a specific data type instead of relying on data type precedence, you can use CONVERT or CAST in the computation to force it (assuming all potential outcomes are compatible with the type you choose). This can be very useful in cases where, by default, you end up with a wider data type than you intended; the most common use case I've seen is when you end up with an INT instead of, say, a BIT:

Active1 AS CASE WHEN something THEN 1 ELSE 0 END, Active2 AS CONVERT(BIT, CASE WHEN something THEN 1 ELSE 0 END) 

In this case Active1 is an INT (4 bytes) while Active2 is a BIT (1 byte - or less, potentially, if it is adjacent to other BIT columns).

like image 184
Aaron Bertrand Avatar answered Sep 17 '22 17:09

Aaron Bertrand