简体   繁体   中英

SQL Server 2000: Updating one table with values from another table

I have a form that displays a list of systems along with their current status. The user can change the status and the date of that status change is stored in a history table. The user can also change the name of the server as a status changes (for example, if a system is replaced due to a lease roll).

The history table stores the details by systemname so if the system name changes on the form, the history also needs to be updated (along with all the historical changes). On the form, there is a hidden field named originalsystemName so we know if the systemname matches or not when the form is saved.

<input type='text' name='systemname'>
  <input type='text' name='originalSystemName'>
  <input type='text' name='status'><input type='submit' type='submit'>

I came up with the following query but I'm getting an error (see below the query).

update SysHistory set  
SystemName = (
    select distinct t.systemname 
    from systemInfo_tmp t, SysHistory h 
    where t.systemname != t.originalSystemName
)    
where systemname in (
    select distinct t1.originalSystemName 
    from systemInfo_tmp t1, SysHistory h1 
    where t1.systemname != t1.originalSystemName
)

Error I'm receiving:

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

Is it possible that this is what you meant? Though unless this is a one-row table, there seems to be a WHERE clause missing.

UPDATE h
    SET SystemName = t.systemname
    FROM SysHistory AS h
    INNER JOIN systemInfo_tmp AS t
    ON h.systemname <> t.originalSystemName;

To update a table with values from another table, this is easily accomplished with a join .

In this scenario, the sysHistory table is joined to the systemInfo_tmp table when the systemInfo_tmp contains a systemName that doesn't match the original, and the sysHistory 's systemName matches.

update sh
set systemName = t.systemName
from
    sysHistory sh join
    systemInfo_tmp t on 
        t.originalSystemName = sh.systemName
        and t.originalSystemName != t.systemName

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