简体   繁体   中英

How to update a column value in one database table using another database table as a reference with SQL

I have one SQL server database which was created using Import/Export Wizard from an Access Database. I then have another SQL database which is based upon the Access database but has a slightly different schema. I am trying to get the data from the simple Access based database into the more complex SQL server schema database. The Access database simply stored the Country as text in Contact table and in my new schema the Contact table has a CountryId which links to the Country table. I've tried to write the SQL to do this:

UDPATE SQLVersion.dbo.Contact
SET CountryId = (SELECT LookupCountry.Id
                 FROM SQLVersion.dbo.Country as LookupCountry, AccessDBVersion.dbo.tblContact as AccessContact
                 WHERE LookupCountry.Name = AccessContact.Country);

This doesn't work because:

Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >= or when the subquery is used as an expression.

I can understand why this error is thrown but I don't know how to form the correct SQL that will allow it to update each row with the value found from the lookup. Can anyone help please?

Looks like you're missing the relation between Contact and tblContact . Assuming those are linked by name , you can rewrite the query in a clearer way like:

update  c
set     countryId = lc.Id
from    SQLVersion.dbo.Contact c
join    AccessDBVersion.dbo.tblContact ac
on      ac.Name = c.Name
join    SQLVersion.dbo.Country lc
on      lc.Name = ac.Country

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