SQL Server computed column select from another table

后端 未结 3 937
说谎
说谎 2021-01-03 19:49

I\'m not to sure what the best way to go about this is, so i\'ll describe what the end goal is, and if a computed column is the answer then please help me go that route, or

相关标签:
3条回答
  • 2021-01-03 20:26

    You won't be able to use columns from another table within a computed column expression. This is an extract from the MSDN documentation.

    A computed column is computed from an expression that can use other columns in the same table.

    You mentioned that your motivation for using a computed column was to increase performance. There are a lot of restrictions but an indexed view might add value here.

    0 讨论(0)
  • 2021-01-03 20:27

    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]
    
    0 讨论(0)
  • 2021-01-03 20:34

    if it is only for display purposes,why not create a view..

    select <<add other columns you need>> mediaspend+basicadviews as totaladviews
    from 
    orders o
    join
    packages p
    on p.packageid=o.orderid
    
    0 讨论(0)
提交回复
热议问题