I tried to figure out how to add the computation expression for a computed column using a user-defined function that I discovered while visiting an online forum.
Here’s an illustration.
— Create a table
CREATE TABLE dbo.Products (
ProductID int IDENTITY (1,1) NOT NULL ,
QtyAvailable SMALLINT,
UnitPrice MONEY);
— Data insertion
INSERT INTO dbo.Products (QtyAvailable, UnitPrice) VALUES (10,128),(11,29),(21,40);
— User-defined function for computation.
CREATE FUNCTION udfComputedColumn
(
@ipvParam1 INT, @ipvParam2 INT
)
RETURNS INT
BEGIN
RETURN @ipvParam1*@ipvParam2
END;
— Altering the table to add a computed column using UDF.
ALTER TABLE dbo.Products ADD InventoryValue AS dbo.udfComputedColumn(QtyAvailable,UnitPrice);
SELECT * FROM dbo.Products;