子查询的问题

 

今天遇到一个很奇怪的SQL问题,SQL语句如下:

select top 1 *,(select top 1 Name_CN from  BaseInfo_Setup where PlantNo=@PlantNo and Type='3') as PlantName_CN  from Payment_Apply
    where
    PlantNo=@PlantNo KS01and
    StartMonth=convert(varchar(6),@StartDate,112) and
    VendorCode=@VendorCode

问题是,实际在BaseInfo_Setup表中是没有PlantNo这个字段的。

单独执行:select top 1 Name_CN from  BaseInfo_Setup where PlantNo=@PlantNo and Type='3',SQL是会报错,没有字段。

但是为什么作为子查询可以呢?

 

开始大家认为是否是不存在的字段,SQL过滤了。有人建议看看

select top 1 *,(select top 1 Name_CN from  BaseInfo_Setup where PlantNo1=@PlantNo and Type='3') as PlantName_CN  from Payment_Apply
    where
    PlantNo=@PlantNo KS01and
    StartMonth=convert(varchar(6),@StartDate,112) and
    VendorCode=@VendorCode

执行后,会出错。

 

后来,有人建议,修改为

select top 1 *,(select top 1 Name_CN from  BaseInfo_Setup  a where a.PlantNo=@PlantNo and a.Type='3') as PlantName_CN  from Payment_Apply
    where
    PlantNo=@PlantNo KS01and
    StartMonth=convert(varchar(6),@StartDate,112) and
    VendorCode=@VendorCode

这样如大家所希望的那样,语句果然出错了。

 

那么只有一个可能了,这个PlantNo是外面表Payment_Apply的字段了。

看来以后还是应该在子查询里面加上指代的,说不定SQL会哪天会出现奇怪的问题。

转载于:https://www.cnblogs.com/wonder223/archive/2011/08/30/2159798.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值