本文介紹了UNION ALL 兩個具有不同列類型的 SELECTs - 預期行為?的處理方法,對大家解決問題具有一定的參考價值,需要的朋友們下面隨著小編來一起學習吧!
問題描述
當我們對具有不同數據類型的兩個表執行 UNION
時,由于 SQL Standard 的預期行為是什么:
What is the expected behaviour due to SQL Standard when we perform UNION
on two tables with different data types:
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
給出
將 varchar 值 'asd' 轉換為數據類型時轉換失敗內部
Conversion failed when converting the varchar value 'asd' to data type int.
但是標準中定義了什么?
but what is defined in the standard?
推薦答案
如果你想在每個查詢中使用 union all
列需要具有相同的類型.C3
必須轉換為 varchar,因為 c1
是 varchar.嘗試以下解決方案
If you want to use union all
columns in every query need to have the same type.C3
must be converteted to varchar because c1
is varchar. Try below solution
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;
我用 "tab1"
替換了 "tab3"
- 我認為這是錯字.
I replaced "tab3"
with "tab1"
- I think it's typo.
這篇關于UNION ALL 兩個具有不同列類型的 SELECTs - 預期行為?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!
【網站聲明】本站部分內容來源于互聯網,旨在幫助大家更快的解決問題,如果有圖片或者內容侵犯了您的權益,請聯系我們刪除處理,感謝您的支持!