如何创建计算列,从另一个表中获取数据

时间:2017-02-04 07:53:52

标签: sql-server tsql

我有两个表A和表B我想在表A中创建Computed列并从表B中获取一个值 这是我的数据的样子

表A

Assembly Item        Component     
   123                400123         
   124                 400124         

表B

Item Id          Thickness           Notes      
400123           0.5           some text about 400123
400124           0.7           some text about 400124

我想得到这样的东西

表A

Assembly Item        Component     Computed Col1      Computed Col1 
   123                400123          0.5         some text about 400123
   124                400124          0.7         some text about 400124

2 个答案:

答案 0 :(得分:1)

您正在寻找JOIN's未计算的列。

您可以为此创建表值函数或视图。

Create View taba_tabB 
As
Select A.[Assembly Item],A.Component ,B.Thickness ,B.Notes
From TableA A 
join TableB B on A.Component = B.[Item Id]

答案 1 :(得分:0)

以下是触发器示例:

CREATE TABLE TableA
(
     AssemblyItem VARCHAR(100),  
     Component VARCHAR(100),
     col1 FLOAT,
     col2 NVARCHAR(max)
)

CREATE TABLE TableB 
(
    ItemID VARCHAR(100),
    Thickness FLOAT,
    Notes NVARCHAR(max)
)

CREATE TRIGGER trg_UpdateRelatedColumn
ON  TableB
AFTER INSERT, DELETE, UPDATE
AS 
BEGIN
    SET NOCOUNT ON;
    UPDATE a SET a.col1=null,a.col2=null FROM TableA AS a INNER JOIN deleted AS d ON a.Component=d.ItemID

    UPDATE a 
    SET a.col1 = i.Thickness,
        a.col2 = i.Notes 
    FROM TableA AS a 
    INNER JOIN inserted AS i ON a.Component = i.ItemID
END
GO

INSERT INTO dbo.TableA(AssemblyItem, Component)
VALUES('123', '400123'), ('124', '400124')

INSERT INTO dbo.TableB(ItemID, Thickness, Notes)
VALUES('400123', 0.5, 'some text about 400123'),
      ('400124', 0.7, 'some text about 400124')


SELECT * 
FROM dbo.TableA

UPDATE dbo.TableB 
SET Notes = Notes + 'aaa' 
WHERE ItemID = '400123'


AssemblyItem    Component   col1    col2
    123         400123      0.5     some text about 400123aaa
    124         400124      0.7     some text about 400124