根据另一个表中的数据更新一个表中的列

时间:2017-09-21 19:57:40

标签: sql sql-server tsql

我有两张桌子:

Hvac_Setup

ID (int)
SuiteType (varchar(50))
Suite (varchar(1000))

套房

ID (int)
SuiteNumber (varchar(10))
SuiteType (varchar(50))

Hvac_Setup表中的示例数据:

ID | SuiteType (description)  | SuiteNumbers
1  | Helmodul A suite A       | 103A,104A (separated by comma, nn suites)
2  | Helmodul A suite A m/hems| 316A,412A,503A,504A,505B,509A,510A 
3  | Helmodul A suite A m/sov | 217A

我希望编写一个SQL查询来更新SuiteType表中的Suites列,其SuiteType表中的Hwac_Setup数据来自SuiteNumbers表{}} SuiteNumbers)匹配。

更新后Suites表的示例数据

ID |    SuiteNumber | SuiteType
---+----------------+---------------------------    
1  |    103A        | Helmodul A suite A
2  |    104A        | Helmodul A suite A
3  |    316A        | Helmodul A suite A m/hems
..
..
n  |    217A        | Helmodul A suite A m/sov

有人可以帮我解释语法吗?

1 个答案:

答案 0 :(得分:0)

试试这个:

set nocount on 

if object_id ('tempdb..#Hvac_Setup') is not null drop table #Hvac_Setup

create table #Hvac_Setup
    (
    ID int,
    SuiteType varchar(50),
    SuiteNumbers varchar(1000)
    )

if object_id ('tempdb..#Suites') is not null drop table #Suites

create table #Suites
    (
    ID int,
    SuiteNumber varchar(10),
    SuiteType varchar(50)
    )

insert #Hvac_Setup values 
    (1, 'Helmodul A suite A', '103A,104A'),
    (2, 'Helmodul A suite A m/hems', '316A,412A,503A,504A,505B,509A,510A'),
    (3, 'Helmodul A suite A m/sov', '217A')

select * from #Hvac_Setup

insert #Suites values
    (1,'103A', 'Helmodul A suite A'),
    (2,'104A', 'Helmodul A suite A'),
    (3,'316A', 'Helmodul A suite A m/hems')

select * from #Suites

update #Suites 
set SuiteType = hs.SuiteType
from #Suites s
inner join #Hvac_Setup as hs 
on hs.SuiteNumbers like '%'+ s.SuiteNumber +'%'

select * from #Suites
顺便说一句:您应该尝试以一致的方式编写问题(表中的Suite或SuiteNumbers?)。