字段有前导零,在 'UNION ALL' 后被删除

Field has Leading Zeros, gets removed after a 'UNION ALL'

我有两个 table 具有相同的字段(数据类型为 Nvarchar(12),NUll)。 这允许字段 allow/show 前导零。

在我执行了 Union ALL 之后,第二个 table 删除了前导零。 我似乎无法弄清楚为什么会这样。

谢谢大家的帮助!

Select Account  , name
From (
select Account
   , name
from table A
Union All
select Account
   , name
from table B)

这是我得到的:

 Account name
 0002    Name1
 0003    Name3
 0004    Name4
 5       Name5
 8       Name6

这就是我想要的

  Account name
 0002    Name1
 0003    Name3
 0004    Name4
 0005    Name5
 0008    Name6

在联合中,每列的数据类型由第一个 SELECT 语句确定。我假设你 AccountTable A 中的数字。要修复,CAST 为 varchar:

Select Account , name From ( select CAST(Account as varchar(20)) as Account , name from table A Union All select Account , name from table B)

正如JNevill所说,每列的数据类型由第一个SELECT语句决定。在您的问题中,您声明每个 table 具有相同的数据类型,即 NVARCHAR(12).

Microsoft's Documentation中,他们说

When data types differ, the resulting data type is determined based on the rules for data type precedence. When the types are the same but differ in precision, scale, or length, the result is based on the same rules for combining expressions.

我的猜测是类型是基于组合表达式的规则。看SQLServer 2017中的data type precedence,NVARCHAR类型排在最后,数字类型优先级高。所以我想在 SQL 服务器中将“0001”作为值在某种程度上转换为数字。

在 UNION ALL 的第一个 SELECT 中将值转换为 NVARCHAR(如 JNevill 所建议的那样)将解决您的问题。

刚刚做了一个快速测试,我无法用 NVARCHAR 类型重现你的问题。即使在我的专栏中指定 NULL。我可以拥有它的唯一方法是如果我的列之一是数字。所以我猜你应该检查 UNION ALL 中 table 的数据类型。或者给出一个示例代码来重现你的问题。

    Create Table test1 (Id int not null identity(1,1), name nvarchar(12) null)
    Create Table test2 (Id int not null identity(1,1), name nvarchar(12) null)

    insert into test1 (name) values ('0001')
    insert into test1 (name) values ('0002')
    insert into test1 (name) values ('3')
    insert into test1 (name) values (NULL)

    insert into test2 (name) values ('0004')
    insert into test2 (name) values ('0005')
    insert into test2 (name) values ('6')

    SELECT name from test1 union all select name from test2