简体   繁体   English

SQL 计算 X + Y = Z

[英]SQL calculation X + Y = Z

New to SQL and I'm sorry if this question has already been asked. SQL 的新手,如果已经问过这个问题,我很抱歉。 I'm looking to create a table with 3 columns X, Y, and Z where I will add the X and Y values to the table.我正在寻找一个包含 3 列 X、Y 和 Z 的表,我将在其中将 X 和 Y 值添加到表中。 Then I'd like to create a stored procedure that will take the row values of X and Y, add them together, and store that value as Z in my table.然后我想创建一个存储过程,它将获取 X 和 Y 的行值,将它们加在一起,并将该值作为 Z 存储在我的表中。 I'd like to be able to add X and Y values whenever I want and then run the store procedure after to calculate Z.我希望能够随时添加 X 和 Y 值,然后在计算 Z 之后运行存储过程。

CREATE TABLE XYZ (
X INT NOT NULL,
Y INT NOT NULL,
Z INT NULL
);
GO

INSERT INTO XYZ (X, Y) VALUES (3, 5);
INSERT INTO XYZ (X, Y) VALUES (5, 8);
INSERT INTO XYZ (X, Y) VALUES (8, 13);

CREATE PROCEDURE CalculateZ
AS
SELECT X, Y, Z = X + Y
INTO XYZ
FROM XYZ;
GO

EXECUTE CalculateZ;
GO

INSERT INTO XYZ (X, Y) VALUES (13, 21);

EXECUTE CalculateZ;
GO

Try this in your stored procedure.在您的存储过程中尝试此操作。 You want an UPDATE to the original table, not an INSERT .您想要对原始表进行UPDATE ,而不是INSERT

update XYZ
set z = x + y

There is no need to do that.没有必要这样做。 Instead, create z as a computed column:相反,将z创建为计算列:

CREATE TABLE XYZ (
    X INT NOT NULL,
    Y INT NOT NULL,
    Z AS (X + Y)
);

Z is then calculated automatically (either when data in the row changes or when queried).然后自动计算Z (当行中的数据更改或查询时)。 There no need to update the table.无需更新表。 No need for a stored procedure either.也不需要存储过程。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM