如何计算到其他表的列

时间:2019-04-13 00:01:09

标签: sql-server database

我想在TBL_CUSTOMERS上创建“ Customers_Balance”列,以显示该存储过程的结果。...

TBL_CUSTOMERS,它具有客户的信息,并且是这样创建的

CREATE TABLE TBL_CUSTOMERS
(
    Customers_ID int PRIMARY KEY, 
    Customers_Name varchar(100) NOT NULL,
    Customers_Phone varchar(100),
    Customers_Address varchar(100),
    Customers_Web varchar(100),
    Customers_Balance decimal(16,0) not null,
);

TBL_CUSTOMERS_DETAILS,它具有所有客户交易的详细信息,并且它是这样创建的

CREATE TABLE TBL_CUSTOMERS_DETAILS
(
    Customers_Details_ID int PRIMARY KEY,
    Customers_ID int,
    Customers_Details_Tybe varchar(50) not null,
    Customers_Details_Date date not null,
    Customers_Details_Amount decimal(16,0) not null,
);

我创建了存储过程来计算客户交易余额总和的结果,并且工作正常,并且像这样创建

CREATE PROC SP_SUM_CUSTOMERS_DETAILS_AMOUNT

@ID INT

AS

SELECT SUM(Customers_Details_Amount)

FROM TBL_CUSTOMERS_DETAILS

Where Customers_ID = @ID

现在

我想在TBL_CUSTOMERS上创建“ Customers_Balance”列,以显示该存储过程的结果。...

我如何制作类似的东西?

2 个答案:

答案 0 :(得分:1)

可以通过其他实现值计算得到的值通常是一个坏主意,因为它存在不一致的风险。

因此,最好将Customers_Balance中的TBL_CUSTOMERS列和过程删除,然后创建一个包含客户数据及其余额的视图。您可以通过联接和聚合来实现。

ALTER TABLE TBL_CUSTOMERS
            DROP COLUMN Customers_Balance;

DROP PROCEDURE SP_SUM_CUSTOMERS_DETAILS_AMOUNT;

CREATE VIEW VW_CUSTOMERS
AS
SELECT C.Customers_ID,
       C.Customers_Name,
       C.Customers_Phone,
       C.Customers_Address,
       C.Customers_Web,
       sum(CD.Customers_Details_Amount) Customers_Balance
       FROM TBL_CUSTOMERS C
            INNER JOIN TBL_CUSTOMERS_DETAILS CD
                       ON CD.Customers_ID = C.Customers_ID
       GROUP BY C.Customers_ID,
                C.Customers_Name,
                C.Customers_Phone,
                C.Customers_Address,
                C.Customers_Web;

答案 1 :(得分:1)

您正在寻找Computed Column

您需要做的是创建一个标量函数而不是存储过程(只需将当前存储过程更改为标量函数),然后在计算列中使用此函数。这将在计算列上为您提供自动更新的结果。

因此,重做您的工作应该是这样的:

-- CREATE THE SCALAR FUNCTION FIRST 
CREATE FUNCTION SUM_CUSTOMERS_DETAILS_AMOUNT (@ID INT)
RETURNS INT 
AS
BEGIN

    RETURN (
        SELECT SUM(Customers_Details_Amount)
        FROM TBL_CUSTOMERS_DETAILS
        WHERE Customers_ID = @ID
    )

END
GO

-- NOW DROP THE CURRENT Customers_Balance COLUMN  
ALTER TABLE TBL_CUSTOMERS
DROP COLUMN Customers_Balance
GO
-- CREATE THE COMPUTED COLUMN WITH THE FUNCTION 
ALTER TABLE TBL_CUSTOMERS
ADD Customers_Balance AS dbo.SUM_CUSTOMERS_DETAILS_AMOUNT (Customers_ID)
GO