当表具有不同的数据类型时,无法将列转换为行

时间:2014-09-18 22:29:15

标签: sql sql-server cross-apply

我有一张如下表:

Create table EmpDetails
(
    ID int primary key,
    DOB datetime not null,
    Name nvarchar(100) not null,
    Salary float not null,
    Email nvarchar(50) not null,
    IsActive bit not null
)

Insert into EmpDetails VALUES (2134, '1985-09-19 03:37:21.757', 'Jack Sparrow', 75000,'abc@gmail.com', 1)

当我尝试使用以下查询将列转换为行时,我收到错误并且查询失败。

select ID, Attrib, Value
from EmpDetails
cross apply
(
select 'DOB', DOB union all
select 'Name', Name union all
select 'Salary', Salary union all
select 'Email', Email union all
select 'IsActive', IsActive
)empd(Attrib, Value);

编辑:我也在下面试过,但得到了同样的错误

select ID, Attrib, Value
from EmpDetails
cross apply
(
values
('DOB', DOB),
('Name', Name),
('Salary', Salary),
('Email', Email),
('IsActive', IsActive)
) empd(Attrib, Value);

错误:

Conversion failed when converting date and/or time from character string.

当我尝试将DOB字段CAST为datetime时,我仍然遇到同样的错误:

select 'DOB', CAST(DOB as datetime)

我该怎么办?任何帮助表示赞赏。

1 个答案:

答案 0 :(得分:1)

由于您正在进行联合,因此所有数据类型都应匹配。尝试以下......

select ID, Attrib, Value
from EmpDetails
cross apply
(
select 'DOB'     , CONVERT(NVARCHAR(50),DOB , 121) union all
select 'Name'    , CAST(Name AS NVARCHAR(50))      union all
select 'Salary'  , CAST(Salary AS NVARCHAR(50))    union all
select 'Email'   , CAST(Email AS NVARCHAR(50))     union all
select 'IsActive', CAST(IsActive AS NVARCHAR(50))
)empd(Attrib, Value);

或者

SELECT ID
       ,Attrib
       ,Value
 FROM 
(
    SELECT ID 
           ,CONVERT(NVARCHAR(50),DOB , 121)  AS DOB
           ,CAST(Name AS NVARCHAR(50))       AS Name
           ,CAST(Salary AS NVARCHAR(50))     AS Salary
           ,CAST(Email AS NVARCHAR(50))      AS Email
           ,CAST(IsActive AS NVARCHAR(50))   AS IsActive
    FROM EmpDetails 
 )t
 UNPIVOT (Value FOR Attrib IN (DOB, Name, Salary, Email, IsActive) )up

结果

╔══════╦══════════╦═════════════════════════╗
║  ID  ║  Attrib  ║          Value          ║
╠══════╬══════════╬═════════════════════════╣
║ 2134 ║ DOB      ║ 1985-09-19 03:37:21.757 ║
║ 2134 ║ Name     ║ Jack Sparrow            ║
║ 2134 ║ Salary   ║ 75000                   ║
║ 2134 ║ Email    ║ abc@gmail.com           ║
║ 2134 ║ IsActive ║ 1                       ║
╚══════╩══════════╩═════════════════════════╝

更新

对于值语法,您需要将所有列值转换/转换为一个类似这样的数据类型...

 select ID, Attrib, Value
from EmpDetails
cross apply
(
values
('DOB'     , CONVERT(NVARCHAR(50),DOB , 121)),
('Name'    , CAST(Name AS NVARCHAR(50)) ),
('Salary'  , CAST(Salary AS NVARCHAR(50))),
('Email'   , CAST(Email AS NVARCHAR(50))),
('IsActive', CAST(IsActive AS NVARCHAR(50)))
) empd(Attrib, Value);