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

跨库UNION ALL视图引发类型转换错误的原因及潜在问题咨询

问题:UNION ALL视图引发varchar转int转换错误的原因及相关场景

背景操作

我有一张存有多年历史记录的不可修改大表,于是将旧数据迁移至独立数据库的表中,并创建了如下视图:

create view qry_big_table as
SELECT id, name FROM db1.dbo.big_table
UNION ALL
SELECT id, name FROM db2.dbo.big_table

原查询逻辑

此前在some_other_view中使用的查询逻辑如下:

SELECT t.*
FROM [other_table] as t
INNER JOIN (
  select convert(int, b.name) as id from [big_table] 
  WHERE ... -- b.name is always integer with this condition
) as b on b.id=t.id

其中[other_table].id为int类型,[big_table].name为varchar类型——虽该字段可能包含任意数据,但WHERE条件可确保返回的name均为整数,因此关联查询从未报错。

问题现象

但将查询中的[big_table]替换为qry_big_table后,出现了转换错误:

Conversion failed when converting the varchar value '12000.00' to data type int

需要说明的是:现有WHERE条件仍能保证qry_big_table返回的name均为整数,并不存在'12000.00'这类值。

已实现的修复方案

我通过调整转换逻辑解决了这个问题,修复后的代码如下:

SELECT t.*
FROM [other_table] as t
INNER JOIN (
  select b.name as id from [big_table] 
  WHERE ... -- b.name is always integer with this condition
) as b on b.id=convert(varchar(9), t.id)

疑问

  • 为何使用UNION ALL创建的视图会引发这个原本不存在的转换错误?
  • 类似场景下还可能出现哪些其他问题?

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.22 12:01:01