Datatype for a Persisted Computed Column? Should I Convert/Cast When Creating It?
-
13-01-2021 - |
Pregunta
What is the Datatype for a Persisted Computed Column?
(a) Does SQL Server automatically infer it?
(b) Also is better to cast it as a datatype, so SQL does not spend time to find what data type it is?
create table dbo.CustomerTransaction
(
CustomerTransactionId int primary key identity(1,1),
CustomerId int,
Price decimal(10,2),
Quantity int,
TotalAmount as CustomerId * Price PERSISTED -- should I cast as cast(CustomerId* Price as decimal(10,2) ??
)
Solución
Information turned into a Community Wiki answer from this question on Stack Overflow: What is the data type of a computed column?
It's determined by the value with the highest datatype precedence.
You can use sql_variant_property
to determine what datatype a literal expression is as per my answer here. e.g. 2147483648
is interpreted as numeric(10,0)
rather than bigint
.
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).
Otros consejos
Try this:
CREATE TABLE dbo.CustomerTransaction
( CustomerTransactionId int primary key identity(1,1),
CustomerId int,
Price decimal(10,2),
Quantity int,
TotalAmount as (cast(CustomerId AS decimal(10,2)) * cast(Price AS decimal(10,2))) PERSISTED
)