日期:2014-05-18  浏览次数:20366 次

cast 问题
SQL code

create table #tmp
(ItemId int not null,
ItemChildName varchar(200) not null,
ItemChild int   null,
Usage   varchar(20) ,
Qty decimal(18,6)
)

insert into #tmp select 1,'a',2,'M',5.55
insert into #tmp select 1,'b',3,'N',151.11
insert into #tmp select 1,'c',4,'W',8


select ItemId,ItemChild,ItemChildName,
case when(Usage='M') Then Qty else CAST(Qty as int) end as Qty  from  #tmp   where ItemId=1


DROP TABLE #tmp

想实现 Usage是M的时候,数量就是存储的Qty,其他情况下 转换成整数,可是结果都是decimal 
这是怎么回事?




------解决方案--------------------
SQL code

create table #tmp
(ItemId int not null,
ItemChildName varchar(10) not null,
ItemChild int   null,
Usage   varchar(20) ,
Qty decimal(18,6)
)

insert into #tmp select 1,'a',2,'M',5.55
insert into #tmp select 1,'b',3,'N',151.11
insert into #tmp select 1,'c',4,'W',8


select ItemId,ItemChild,ItemChildName,
case when Usage='M' Then cast(Qty as varchar(10)) 
else cast(cast(Qty as int) as varchar(10)) end as Qty  
from  #tmp  where ItemId=1


ItemId      ItemChild   ItemChildName Qty
----------- ----------- ------------- ----------
1           2           a             5.550000
1           3           b             151
1           4           c             8

(3 row(s) affected)