-3

我必须编写 SQL 语句来切换 in 的值,CompanyName以便table1当前具有该值的所有行都具有'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'
4

3 回答 3

3

不确定这是您想要的:

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')
于 2013-11-05T06:01:04.613 回答
0

当您反转这些值时,您需要进行 3 个不同的更新(3 个步骤),如下所示;

Step1:更改现有“Linens and Things”的值;

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

Step2:将供应商“Lamps and Lighting”修改为“Linens and Things”;

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

Step3:将最初“Linens and Things”的供应商修改为“Lamps and Lighting”;

Update table1 set CompanyName = "Lamps and Lighting"
where  CompanyName = "x"
于 2013-11-05T05:36:07.487 回答
0

T-SQL 的 UPDATE 语句有一个 FROM 子句,允许您在更新表之前计算它。对于这种情况,我们可以将新名称计算为AlternateCompanyName和 set 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')
于 2013-11-05T06:34:27.753 回答