我有广播,代理和广告表:
CREATE TABLE Broadcasts (
Broadcast_code INT IDENTITY(1,1)PRIMARY KEY,
Minute_cost SMALLMONEY NOT NULL
);
CREATE TABLE Agents (
Agent_code INT IDENTITY(1,1)PRIMARY KEY,
Agent_percent FLOAT NOT NULL,
);
CREATE TABLE Advert (
Advert_code INT IDENTITY(1,1)PRIMARY KEY,
Agent_commission AS ((Minute_cost * Duration_in_minutes) / Agent_percent),
Broadcast_code INT FOREIGN KEY REFERENCES Broadcasts (Broadcast_code) NOT NULL,
Agent_code INT FOREIGN KEY REFERENCES Agents (Agent_code) NOT NULL
);
我想计算一个计算列:
Agent_commission AS (((Minute_cost * Duration_in_minutes) / Agent_percent)
我尝试使用VIEWS,TRIGGERS和UDF。但我不能这样做。
我需要最简单的方法,因为这是一个培训项目。 感谢。
答案 0 :(得分:2)
计算列不能直接引用其他表中的列。一种选择是编写用户定义的标量函数来计算佣金。
您还有两个选择:
哪个最好取决于佣金的使用方式。我建议你从一个你想要的逻辑视图开始。您可能会发现需要来自多个表的列。
答案 1 :(得分:0)
您可以按照以下步骤进行操作
创建表
CREATE TABLE Advert (
Advert_code INT IDENTITY(1,1)PRIMARY KEY,
Agent_commission INT,
Broadcast_code INT FOREIGN KEY REFERENCES Broadcasts (Broadcast_code) NOT NULL,
Agent_code INT FOREIGN KEY REFERENCES Agents (Agent_code) NOT NULL
);
选择所需的列
SELECT
NULL AS Advert_code,
((B.Minute_cost * Duration_in_minutes) / A.Agent_percent),
B.Broadcast_code,
A.Agent_code
FROM Broadcasts B
INNER JOIN Agents A
ON (B.Broadcast_code = A.Agent_code );
使用select查询,您可以插入新表
INSERT INTO Advert
SELECT
NULL AS Advert_code,
((B.Minute_cost * Duration_in_minutes) / A.Agent_percent),
B.Broadcast_code,
A.Agent_code
FROM Broadcasts B
INNER JOIN Agents A
ON (B.Broadcast_code = A.Agent_code );
很少澄清,
*从哪里获得Duration_in_minutes
*什么是Advert_code,现在选择null,如果需要,你可以使用oracle序列或从另一个表中选择。
您也可以使用相同的选择查询来创建视图