You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

SQL子查询触发Msg 116 Level 16报错问题咨询

报错原因
  • 核心语法问题:内层子查询使用select *返回Folio表的全字段,而外层where FolioID = 子查询的语法要求子查询只能返回单个字段的结果,违反了“子查询未用EXISTS引入时,选择列表仅可指定一个表达式”的SQL语法规则。
  • 额外潜在问题:若符合日期筛选条件的Folio记录超过1条,即使用select FolioID替换select *,等于号=也会因无法匹配多个返回值触发新的报错。
可行解决方法

根据实际业务场景选择对应方案即可:

方案1:确定匹配的FolioID唯一

仅修改内层子查询的返回字段为FolioID即可:

select *
from Folio_Guest
where FolioID = (
    select FolioID
    from Folio
    where ArrivalDate between '20190101' and '20210901'
)

方案2:匹配的FolioID可能不唯一

将等于号替换为in适配多值匹配场景:

select *
from Folio_Guest
where FolioID in (
    select FolioID
    from Folio
    where ArrivalDate between '20190101' and '20210901'
)

方案3:关联查询(推荐)

需要同时使用Folio表其他字段时,用关联查询写法性能更优,逻辑更清晰:

select fg.*
from Folio_Guest fg
inner join Folio f 
    on fg.FolioID = f.FolioID
where f.ArrivalDate between '20190101' and '20210901'

方案4:使用EXISTS语法

对应报错提示的EXISTS引入规则,写法如下:

select *
from Folio_Guest fg
where exists (
    select 1
    from Folio f
    where f.FolioID = fg.FolioID
    and f.ArrivalDate between '20190101' and '20210901'
)

内容的提问来源于stack exchange,提问作者Omar Elfky

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.05 10:30:04