简体   繁体   English

使用带有更新语句的子查询

[英]Use sub-query with update statement

I have to update the top 2 rows of a column based on the select top 2 statement with some expressions.我必须使用一些表达式更新基于 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]                                    
                                   )

With the above query I'm getting this error通过上面的查询,我收到了这个错误

Subquery returned more than 1 value.子查询返回超过 1 个值。 This is not permitted when the subquery follows =, ,=, <, <=, >.当子查询跟随 =, ,=, <, <=, > 时,这是不允许的。 >= or when the subquery is used as an expression. >= 或当子查询用作表达式时。

I have to use this in both SQL Server and in Oracle.我必须在 SQL 服务器和 Oracle 中使用它。

in sql-server you can use cte + select data first then update it.在 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 2 行受影响
select * from HOTELS;
 | | NAME |姓名 | |:------------ | |:------------ | | | ABCDExxxxxEFG | ABCDExxxxxxEFG | | | HIJKLxxxxxMOP | HIJKLxxxxx澳门币 |

db<>fiddle here db<> 在这里摆弄


edit for oracle version编辑 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 2 行受影响
update Table1 set name = SUBSTR(Name, 1, 5) || 'xxxxx' || SUBSTR(Name, LENGTH(Name) - 2, LENGTH(Name)-1) where rownum <= 2
 2 rows affected 2 行受影响
select * from Table1
 | | NAME |姓名 | |:------------ | |:------------ | | | ABCDExxxxxEFG | ABCDExxxxxxEFG | | | HIJKLxxxxxMOP | HIJKLxxxxx澳门币 |

db<>fiddle here db<> 在这里摆弄

In your subquery you have top 2 change the limit to 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
  )

And if you don't want the where condition then don't use it eg:如果您不想要 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]

  )

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM