简体   繁体   中英

Setting multiple rows in one table equal to multiple rows in another table based on multiple column values being equal

I am trying to run a rather convoluted query. Two tables are out of sync. In one step of the processing, a 16 digit value is copied from one table to the other, and is getting truncated to just 10 digits.

I'm using a few pieces of information to copy the full 16 digit number over. I'm trying to find anywhere where the 10 digit value matches the first 10 digits of the 16 digit value, and three other pieces of information in these two tables match. Combined, they give almost 100% certainty that we have a unique entry. This is the current iteration of my query:

UPDATE DB1.TABLE1
SET ID =
(
SELECT b.ID
FROM DB2.TABLE1 b
INNER DB1.TABLE1 a 
ON left(b.ID, 10) = a.ID
WHERE len(a.ID) = 10
AND a.STORE = b.STORE
AND a.DOCTYPE = b.DOCTYPE
AND a.DOCDATE = b.DOCDATE
)

The problem is, it's telling me the subquery is returning multiple results. But I want multiple results. I tried adding another WHERE statement after the parenthesis, and duplicating the last four lines of the subquery, but that's not working either. I also tried using WHERE EXISTS and duplicating the entire SELECT statement, but that gives em the multiple results error as well. What am I missing here?

Your statement is attempting to update every row in DB1.TABLE1 to what's returned by the subquery. Not only is that not what you want, but the statement fails because the subquery is returning multiple values.

What you need to do is correlate the two tables as part of the update statement, like this:

UPDATE DB1.TABLE1
SET ID = b.ID
FROM DB1.TABLE1 a
  INNER JOIN DB2.TABLE1 b
  ON left(b.ID, 10) = a.ID
    AND a.STORE = b.STORE
    AND a.DOCTYPE = b.DOCTYPE
    AND a.DOCDATE = b.DOCDATE
WHERE len(a.ID) = 10

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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