sql - 使用带有更新语句的子查询
问题描述
我必须使用一些表达式根据 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 中使用它。
解决方案
在 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<>在这里摆弄
推荐阅读
- java - 意外循环中的 Java 输出/输入,即使我没有故意将其放入循环中
- gremlin - 如何在 Gremlin 遍历中使用 sideEffect 和 dedup?
- cors - 在 Netlify 函数中强制同源?(cors)
- javascript - 为什么我的 javascript 不能在 wordpress 中工作(我是否以正确的方式链接它)
- google-cloud-platform - 如何设置 GCS 存储桶的限制
- sql - postgresql 可以共享只读会话吗?
- php - php代码在所有浏览器中的工作方式都不一样
- flutter - Flutter App 未构建(Gradle 问题)| 卡在 assembleDebug
- wpf - WPF - 当可见性为折叠时如何不更新布局
- pointers - 用“void*”转换“char”指针并取消引用它