在库存交易表中强制执行规则

时间:2012-09-08 17:54:57

标签: sql sql-server database-design

我正在创建一个假的股票市场类型数据库,Transaction表需要某种逻辑来强制执行某些规则。这是我正在使用的Transaction表:

Id  AccountId   Action  Qty Price   Amount
1   1           SELL    30  $1.00   $30.00
2   2           BUY     30  $1.00   -$30.00
3   1           SELL    20  $2.00   $40.00
4   3           BUY     20  $2.00   -$40.00
5   3           DEPOSIT            $100.00

正如您在此处所见BUY/SELL行动必须有QtyPriceAmount应该计算。 DEPOSIT操作不需要QtyPrice,因为这只是用户将钱存入Account

我正在考虑使用某种触发器来做到这一点。有更好的做法吗?

1 个答案:

答案 0 :(得分:1)

在SQL Server 2012中测试。(库存符号被省略。)

create table stock_transactions (
  trans_id integer primary key,
  trans_ts datetime not null default current_timestamp,
  account_id integer not null, -- references accounts, not shown

  -- char(1) keeps the table narrow, while avoiding a needless
  -- join on an integer. 
  -- (b)uy, (s)ell, (d)eposit
  action char(1) not null check (action in ('b', 's', 'd')),

  qty integer not null check (qty > 0),

  -- If your platform offers a special data type for money, you
  -- should probably use it. 
  price money not null check (price > cast(0.00 as money)),

  -- Assumes it's not practical to calculate amounts on the fly
  -- for many millions of rows. If you store it, use a constraint
  -- to make sure it's right. But you're better off starting
  -- with a view that does the calculation. If that doesn't perform
  -- well, try an indexed view, or (as I did below) add the 
  -- "trans_amount" column and check constraint, and fix up
  -- the view. (Which might mean just including the new "trans_amount"
  -- column, or might mean dropping the view altogether.)
  trans_amount money not null,

  -- Only (b)uys always result in a negative amount.
  check ( 
    trans_amount = (case when action = 'b' then qty * price * (-1)
                         else                   qty * price
                    end )
  ),

  -- (d)eposits always have a quantity of 1. Simple, makes logical 
  -- sense, avoids NULL and avoids additional tables.
  check ( 
    qty = (case when action = 'd' then 1 end)
  )
);

insert into stock_transactions values
(1, current_timestamp, 1, 's', 30,   1.00,   30.00),
(2, current_timestamp, 2, 'b', 30,   1.00,  -30.00),
(3, current_timestamp, 1, 's', 20,   2.00,   40.00),
(4, current_timestamp, 3, 'b', 20,   2.00,  -40.00),
(5, current_timestamp, 3, 'd',  1, 100.00,  100.00);

但看看发生了什么。现在我们已经将存款添加为一种交易,这不再是股票交易表。现在它更像是一个账户交易表。

您需要的不仅仅是CHECK约束,以确保帐户中有足够的内容来购买帐户持有人想要购买的任何内容。

在SQL Server中,有关聚簇索引的决策很重要。给出一些思考和测试。我希望您经常查询帐号ID号。