Deprecated
Deprecated

Reputation: 163

Correlated Update

I'm trying to update one table using fields from another:

Update x
From y
Set 1=y.1, 2=y.2, 3=y.3
Where y.4="*Cash*" and y.5="*Use*"

Is this possible? Or do I have to use an Inner Join or a Subquery? I keep getting an error in my Update Syntax: "Missing or Invalid Option."

Upvotes: 0

Views: 79

Answers (1)

Justin Cave
Justin Cave

Reputation: 231781

You seem to be asking for something like

UPDATE x
   SET (col1, col2, col3) = (select y.col1, y.col2, y.col3
                               from y
                              where y.col4 = '*Cash*'
                                and y.col5 = '*Use*')

Normally, there would be some additional condition that relates the tables x and y. If the query against y returns a single row and you want to update every row of x with that single row of data, that is not necessary. But normally, you'd have something like

UPDATE x
   SET (col1, col2, col3) = (select y.col1, y.col2, y.col3
                               from y
                              where y.col4 = '*Cash*'
                                and y.col5 = '*Use*'
                                and x.someKey = y.someKey)

If you only want to update the rows in x that have a matching row in y

UPDATE x
   SET (col1, col2, col3) = (select y.col1, y.col2, y.col3
                               from y
                              where y.col4 = '*Cash*'
                                and y.col5 = '*Use*'
                                and x.someKey = y.someKey)
 WHERE EXISTS( select 1
                 from y
                where y.col4 = '*Cash*'
                  and y.col5 = '*Use*'
                  and x.someKey = y.someKey)

Upvotes: 2

Related Questions