SQL Server表中的计算列的公式中能否引用别的表中的列,如何引用?

解决方案 »

  1.   


    create table ta(id int)
    go
    create function f_d()
    returns int
    as
    begin
        declare @d int
        select @d = sum(id) from ta
        return @d
    end
    go
    create table tb(id int,col as (dbo.f_d()))
    goinsert ta select 1
    insert ta select 2
    insert tb(id) select 2
    select * from tb
    drop table ta,tb
    drop function f_d
    /*id          col         
    ----------- ----------- 
    2           3(所影响的行数为 1 行)
    */
      

  2.   

    引用本表的列参与  运算
    create table ta(id int)
    go
    create function f_d(@id int)
    returns int
    as
    begin
        declare @d int
        select @d = sum(id) from ta
        return @d * @id
    end
    go
    create table tb(id int,col as (dbo.f_d(id)))
    goinsert ta select 1
    insert ta select 2
    insert tb(id) select 2
    select * from tb
    drop table ta,tb
    drop function f_d
    /*id          col         
    ----------- ----------- 
    2           6(所影响的行数为 1 行)*/
      

  3.   


    create table ta(id int)
    go
    create function f_d(@id int)
    returns int
    as
    begin
        declare @d int
        select @d = sum(id) from ta
        return @d * @id
    end
    go
    create table tb(id int,col as (dbo.f_d(id)))
    goinsert ta select 1
    insert ta select 2
    insert tb(id) select 2
    insert tb(id) select 4
    insert tb(id) select 5
    select * from tb
    drop table ta,tb
    drop function f_d
    /*
    id          col         
    ----------- ----------- 
    2           6
    4           12
    5           15(所影响的行数为 3 行)
    */
      

  4.   


    Create table aa(id int ,name as id)insert into aa (Id) select '1'select * from aa