如何编写SQL UPDATE语句同时更新?

时间:2013-11-05 04:53:52

标签: sql sql-server

我必须编写SQL语句来切换CompanyNametable1的值,以便当前具有值'Linens and Things'的所有行都具有值'Lamps and Lighting',并且所有当前具有值'Lamps and Lighting'的行将具有值'Linens and Things'

我的表目前看起来像这样:

id  CompanyName
--- ----------------------
1   'Linens and Things'
2   'Linens and Things'
3   'Lamps and Lighting'
4   'Lamps and Lighting'
5   'A Different Vendor'

更新后,它应如下所示:

id  CompanyName
--- ----------------------
1   'Lamps and Lighting'
2   'Lamps and Lighting'
3   'Linens and Things'
4   'Linens and Things'
5   'A Different Vendor'

3 个答案:

答案 0 :(得分:2)

不确定这是你想要的:

UPDATE table1
SET CompanyName = CASE WHEN CompanyName = 'Linens and Things' THEN 'Lamps and Lighting'
                       WHEN CompanyName = 'Lamps and Lighting' THEN 'Linens and Things'
                       ELSE CompanyName
                       END
WHERE CompanyName IN ('Linens and Things','Lamps and Lighting')

答案 1 :(得分:0)

当您反转这些值时,您需要按照以下步骤进行3次不同的更新(3个步骤);

步骤1:更改现有“亚麻布和物品”的值;

Update table1 set CompanyName = "x"
where  CompanyName = "Linens and Things"

步骤2:将供应商的灯具和灯具'修改为'亚麻布和物品';

Update table1 set CompanyName = "Linens and Things"
where  CompanyName = "Lamps and Lighting"

步骤3:将最初“亚麻布和东西”的供应商修改为“灯具和灯具”;

Update table1 set CompanyName = "Lamps and Lighting"
where  CompanyName = "x"

答案 2 :(得分:0)

T-SQL UPDATE语句有一个FROM子句,可以在更新表之前计算表。对于这种情况,我们可以将新名称计算为AlternateCompanyName并设置CompanyName=AlternateCompanyName

UPDATE table1
SET CompanyName = ComputedTable.AlternateCompanyName
FROM (
    SELECT
        id,
        CompanyName,
        CASE
          WHEN CompanyName = 'Linens and Things' THEN 'Lamps and Lighting'
          WHEN CompanyName = 'Lamps and Lighting' THEN 'Linens and Things'
        END AS AlternateCompanyName
    FROM table1
) AS ComputedTable
JOIN table1 ON table1.id = ComputedTable.id
WHERE table1.CompanyName IN ('Lamps and Lighting', 'Linens and Things')