UPDATE t1 SET Quantity=Quantity-t2.QuantityMinusValue
FROM Table1 t1
INNER JOIN Table2 t2 ON t1.Id=t2.Id
Frågan#1
SqlServer 2005
Vill köra en UPDATE på Table1, och minska dess Quantity värde med det värdet som Table2.QuantityMinusValue har, om den har något för det Table1.Id:t.
CREATE TABLE [Table1] (
[Id] [int] IDENTITY (1, 1) NOT FOR REPLICATION NOT NULL ,
[Quantity] [int] NOT NULL ,
CONSTRAINT [PK_Table1] PRIMARY KEY CLUSTERED
(
[Id]
) ON [PRIMARY]
) ON [PRIMARY]
GO
CREATE TABLE [Table2] (
[Id] [int] IDENTITY (1, 1) NOT FOR REPLICATION NOT NULL ,
[Table1Id] [int] NOT NULL ,
[QuantityMinusValue] [int] NOT NULL ,
CONSTRAINT [PK_Table2] PRIMARY KEY CLUSTERED
(
[Id]
) ON [PRIMARY]
) ON [PRIMARY]
GO
INSERT INTO dbo.[Table1](Quantity) VALUES(3);
INSERT INTO dbo.[Table1](Quantity) VALUES(25);
INSERT INTO dbo.[Table1](Quantity) VALUES(18);
INSERT INTO dbo.[Table1](Quantity) VALUES(9);
INSERT INTO dbo.[Table2](Table1Id, QuantityMinusValue) VALUES(2, 13);
INSERT INTO dbo.[Table2](Table1Id, QuantityMinusValue) VALUES(4, 8);
SELECT * FROM dbo.[Table1]
SELECT * FROM dbo.[Table2]