将子查询与更新语句一起使用

时间:2019-11-05 07:11:25

标签: sql sql-server oracle

我必须根据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]                                    
                                   )

通过上面的查询,我收到此错误

  

子查询返回了多个值。当子查询遵循=,!=,<,<=,>,> =或将子查询用作表达式时,不允许这样做。

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

2 个答案:

答案 0 :(得分:1)

在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 rows affected
select * from HOTELS;
| NAME          |
| :------------ |
| ABCDExxxxxEFG |
| HIJKLxxxxxMOP |

db <>提琴here


编辑oracle版本

CREATE TABLE Table1
  ("NAME" varchar2(80))
;
INSERT ALL 
  INTO Table1 ("NAME")
       VALUES ('ABCDEFG')
  INTO Table1 ("NAME")
       VALUES ('HIJKLMOP')
SELECT * FROM dual
;
2 rows affected
update Table1
set name = SUBSTR(Name, 1, 5) || 'xxxxx' || SUBSTR(Name, LENGTH(Name) - 2, LENGTH(Name)-1)
where rownum <= 2
2 rows affected
select * from Table1
| NAME          |
| :------------ |
| ABCDExxxxxEFG |
| HIJKLxxxxxMOP |

db <>提琴here

答案 1 :(得分:1)

在子查询中,您将前2个值的限制更改为1

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

如果您不希望where条件,请不要使用它,例如:

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

  )