首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 数据库 > SQL Server >

SQL怎的去除表达式里的*号

2013-03-16 
SQL怎样去除表达式里的*号?怎样处理这样的字符,有三个字段A1,A2,A3,A4:A1[float]A2[float]A3[float]A4[nva

SQL怎样去除表达式里的*号?
怎样处理这样的字符,有三个字段A1,A2,A3,A4:
A1[float]   A2[float]   A3[float]   A4[nvarchar]
------------------------------------------------
12          23          45          12*23*45
0           12          44          12*44
0           88          null        88
...

A4的等于A1*A2*A3,如果某个字段等于0则不拼凑,只等于非0或非null的数值加上*号组成。
[解决办法]

if object_id('[TB]') is not null drop table [TB]
go
create table [TB] (A1 int,A2 int,A3 int,A4 AS CONVERT(VARCHAR,A1)+'*'+CONVERT(VARCHAR,A2)+'*'+CONVERT(VARCHAR,A3))  --lz把这个地方重新修改一下判断null及0值处理一下即可。
insert into [TB]
select 12,23,45 union all
select 0,12,44 union all
select 0,88,null

select * from [TB]

[解决办法]
这个意思?
select a1,a2,a3,a4=
replace(replace(case when isnull(a1,0)=0 then 'a' else rtrim(a1) end+'*'+case when isnull(a2,0)=0 then 'a' else rtrim(a2) end+'*'+case when isnull(a3,0)=0 then 'a' else rtrim(a3) end,'a*',''),'*a','')
from tb
[解决办法]
select (case when A1 is null or A1=0 then '' 
when (A2 is not null and A2<>0) or (A3 is not null and A3<>0) then A1+'*'
else A1 end)
+(case when A2 is null or A2=0 then '' 
when A3 is not null and A3<>0 then A2+'*'
else A2 end)
+(case when A3 is null or A1=0 then '' else A3 end)
as A4
[解决办法]

declare @T table([A1] int,[A2] int,[A3] int)
insert @T
select 12,23,45 union all
select 0,12,44 union all
select 0,88,null union all
select 4,0,5 union all
select 6,null,8 union all
select 0,0,0

select 
replace(isnull(ltrim(iif([A1]=0,null,[A1]))+'*','')+
isnull(ltrim(iif([A2]=0,null,[A2])),'')+
isnull('*'+ltrim(iif([A3]=0,null,[A3])),''),'**','*')
from @T t 
/*
12*23*45
12*44
88
4*5
6*8
*/

热点排行