首页 > 解决方案 > 使用带有更新语句的子查询

问题描述

我必须使用一些表达式根据 select top 2 语句更新列的前 2 行。

update top(2) [Travel].[dbo].[HOTELS]
set [Travel].[dbo].[HOTELS].NAME = (select top(2) SUBSTRING(Name, 1, 5) + 'xxxxx' + SUBSTRING(Name, LEN(Name) - 2, LEN(Name)) AS column1
                                    from [Travel].[dbo].[HOTELS]                                    
                                   )

通过上面的查询,我收到了这个错误

子查询返回超过 1 个值。当子查询跟随 =、!=、<、<=、>、>= 或子查询用作表达式时,这是不允许的。

我必须在 SQL Server 和 Oracle 中使用它。

标签: sqlsql-serveroracle

解决方案


在 sql-server 中,您可以使用cte + select data first然后更新它。

CREATE TABLE HOTELS
  ([NAME] varchar(14))
;

INSERT INTO HOTELS
  ([NAME])
VALUES
  ('ABCDEFG'),
  ('HIJKLMOP')
;
GO
with cte as (
    select top 2 NAME, SUBSTRING(Name, 1, 5) + 'xxxxx' + SUBSTRING(Name, LEN(Name) - 2, LEN(Name)) AS column1
    from [HOTELS]
)
update cte set NAME = column1;
GO
2 行受影响
select * from HOTELS;
| 姓名 |
| :------------ |
| ABCDExxxxxxEFG |
| HIJKLxxxxx澳门币 |

db<>在这里摆弄


编辑oracle版本

CREATE TABLE Table1
  ("NAME" varchar2(80))
;
INSERT ALL 
  INTO Table1 ("NAME")
       VALUES ('ABCDEFG')
  INTO Table1 ("NAME")
       VALUES ('HIJKLMOP')
SELECT * FROM dual
;
2 行受影响
update Table1
set name = SUBSTR(Name, 1, 5) || 'xxxxx' || SUBSTR(Name, LENGTH(Name) - 2, LENGTH(Name)-1)
where rownum <= 2
2 行受影响
select * from Table1
| 姓名 |
| :------------ |
| ABCDExxxxxxEFG |
| HIJKLxxxxx澳门币 |

db<>在这里摆弄


推荐阅读