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?
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.
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.
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).
The data type of a column defines what value the column can hold: integer, character, money, date and time, binary, and so on.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With