当我们UNION在具有不同数据类型的两个表上执行时,由于SQL Standard而产生的预期行为是什么:
UNION
create table "tab1" ("c1" varchar(max)); create table "tab2" ("c3" integer); insert into tab1 values(N'asd'), (N'qweqwe'); insert into tab2 values(123), (345); select c_newname as myname from ( select "c1" as c_newname from "tab1" union all select "c3" from "tab2" ) as T_UNI;
MS SQL Server 给
MS SQL Server
将varchar值“ asd”转换为数据类型int时,转换失败。
但是标准中定义了什么?
如果要union all在每个查询中使用列,则必须具有相同的类型。C3必须转换为varchar,因为它c1是varchar。请尝试以下解决方案
union all
C3
c1
create table "tab1" ("c1" varchar(max)); create table "tab2" ("c3" integer); insert into tab1 values(N'asd'), (N'qweqwe'); insert into tab2 values(123), (345); select c_newname as myname from ( select "c1" as c_newname from "tab1" union all select cast("c3" as varchar(max)) from "tab2" ) as T_UNI;
我替换"tab3"为"tab1"-我认为这是拼写错误。
"tab3"
"tab1"