SQL Server computed column select from another table

I know this answer comes two years late, but just to help anyone who googles and finds this post:

It is perfectly legal to define a user-defined function and use it as the computed value. This function may contain select statements from other tables.

CREATE FUNCTION dbo.getAdViews(@packageId int)
RETURNS INT
AS
BEGIN
    declare @bav int
    select @bav = BaseAdViews from Packages where PackageId = @packageId
    RETURN @bav
END

Then in your computed column, just use the expression dbo.getSumAdViews(PackageId)+MediaSpend as so:

CREATE TABLE [dbo].[Orders](
    [OrderId] [int] IDENTITY(1,1) NOT NULL,
    [PackageId] [int] NOT NULL,
    [MediaSpend] [int] NULL,
    [TotalAdViews] AS dbo.getAdViews(PackageId)+MediaSpend
) ON [PRIMARY]

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)