ssl
ssl

Reputation:

how to write sql query? for ms sql server

I need to write a sql query that adds one column from one database (DB1) to another column and the sum is save in that column in the second database(DB2). where userIds are the same

DB1
TableA
UserId People


DB2
TableB
Amount UserId

it would be something like this

DB2.TableB.Amount = DB2.TableB.Amount + DB1.TableA.People

Upvotes: 0

Views: 776

Answers (3)

Brimstedt
Brimstedt

Reputation: 3140

Do you mean:

UPDATE b
SET    Amount = b.Amount + a.People
FROM DB2.dbo.TableB b
INNER JOIN DB1.dbo.TableA a
  ON  a.UserId = b.UserId

dbo = owner of table, it can also be unspecified: DB1..TableA

Upvotes: 4

cjk
cjk

Reputation: 46425

This is untested:

INSERT INTO DB2.dbo.TableB
SELECT SUM(DB2.TableB.Amount + DB1.TableA.People), UserID
FROM DB1.dbo.TableA
GROUP BY UserID

Upvotes: 0

Lieven Keersmaekers
Lieven Keersmaekers

Reputation: 58441

INSERT INTO DB2.dbo.TableB
SELECT COUNT(*), UserID
FROM DB1.dbo.TableA
GROUP BY UserID

Upvotes: 0

Related Questions