如何从SELECT语句更新列?

时间:2019-04-11 16:39:58

标签: sql sql-server

我正在尝试为多个用户更新一列。我从名字中提取了3个字符,从名字中提取了2个字符,并创建了一个别名。如何使用创建的别名中的数据与另一个值(例如联系人的序列号)同时更新另一个表中的列?

Select DISTINCT FULLNAME,
    concat(Substring(FULLNAME, 1, 3), substring(FULLNAME, charindex(' ', 
    FULLNAME)+1, 2)) as PIC,
    CONTACT.SERIALNO,
    PASSWD
From CONTACT
    Join CONTPOINT on CONTPOINT.SERIALNO = CONTACT.SERIALNO
        and CONTPOINT.CONTTYPE = CONTACT.CONTTYPE
    Join CONTLIST on CONTLIST.REFSERIALNO = CONTACT.SERIALNO
        and CONTLIST.REFCONTTYPE = CONTACT.CONTTYPE
Where
    --left(CONTACT.fullname,4) in ()
    PASSWD in ('ADDRESS FOR THE SITE', 'ADDRESS OF SITE', 'ADDRESS OF 
    SITE', 'ADDRESS FOR THE SITE', 'ADDRESS OF SITE', 'ADDRESS OF SITE', 
    'THE SITE"S STREET NAME')

1 个答案:

答案 0 :(得分:0)

您可以使用UPDATE FROM语法。 让我们将您的SELECT语句称为ORIGINAL,并将您要更新的“其他表”称为OTHER。

要使用UPDATE FROM

UPDATE
    OTHER
  SET 
    COLUMN_TO_UPDATE = ORIGINAL.PIC
  FROM 
    OtherTable OTHER
    INNER JOIN  
      (Select DISTINCT FULLNAME,
              concat(Substring(FULLNAME, 1, 3), substring(FULLNAME, charindex(' ', 
              FULLNAME)+1, 2)) as PIC,
              CONTACT.SERIALNO,
              PASSWD
          From CONTACT
              Join CONTPOINT on CONTPOINT.SERIALNO = CONTACT.SERIALNO
                  and CONTPOINT.CONTTYPE = CONTACT.CONTTYPE
              Join CONTLIST on CONTLIST.REFSERIALNO = CONTACT.SERIALNO
                  and CONTLIST.REFCONTTYPE = CONTACT.CONTTYPE
          Where
              --left(CONTACT.fullname,4) in ()
              PASSWD in ('ADDRESS FOR THE SITE', 'ADDRESS OF SITE', 'ADDRESS OF 
              SITE', 'ADDRESS FOR THE SITE', 'ADDRESS OF SITE', 'ADDRESS OF SITE', 
              'THE SITE"S STREET NAME')) ORIGINAL
      ON (ORIGINAL.SERIALNO = OTHER.SERIALNO)
  WHERE 
    <conditions on OTHER to update>;