sql查询无法使用自动计算列创建表

时间:2017-04-06 19:36:50

标签: sql-server

[在此处输入图片说明] [1] enter image description here亲爱的所有程序员请帮助我。我无法在sql server 2008中创建表,请任何人帮我这个。相信我,我是在全力以赴之后来到这里的。这是我的代码:

CREATE TABLE [dbo].[STransactions](
    [ATId] [int] IDENTITY(1,1) NOT NULL,
    [ItemId] [nvarchar](max) NOT NULL,
    [ADeposit] [int] NULL,
    [ACredit] [int] NULL,
    [ABalance]  AS sum([ADeposit]-[ACredit])
) ON [PRIMARY]

GO

1 个答案:

答案 0 :(得分:1)

您不需要sum();只是减法。

CREATE TABLE [dbo].[STransactions](
    [ATId] [int] IDENTITY(1,1) NOT NULL,
    [ItemId] [nvarchar](max) NOT NULL,
    [ADeposit] [int] NULL,
    [ACredit] [int] NULL,
    [ABalance]  AS ([ADeposit]-[ACredit])
) ON [PRIMARY]

GO

对于像您的图片一样有运行余额的视图:

create view dbo.STransactions_wBalance as 
  select
      t.AtID
    , t.ItemId
    , t.ADeposit
    , t.ACredit
    , x.Balance
  from dbo.STransactions t
    cross apply (
    select Balance = sum(ADeposit-ACredit)
    from dbo.STransactions as i
    where i.ItemId = t.ItemId
      and i.AtID  <= t.AtID
    ) x;
go

然后查询视图而不是表。