1. 如何在sqlserver 中实现decode 的方法
ORACLE的decode功能绝对不如case那么灵活﹐oracle8i以上版本都提供了case语法﹐
再说decode的实现是commandline的方式传入,SQL没有这种实现﹐当然可以摭展存储
过程的方式实现﹐用DELPHI写DLL﹐加载到企业管理器中。
2. 如何在sqlserver中实现oracle decode的功能,并写成一个函数
解决思想:1.把输入参数按照逗号分割
2.实现decode功能
1.字符串分割函数
create function dbo.getstrofindex (@str varchar(1000),@index int =0)
returns varchar(1000)
as
begin
declare @str_return varchar(1000)
declare @start int
declare @next int
declare @location int
select @start =1
select @next =1
select @location = charindex(',',@str,@start)
while (@location <>0 and @index > @next )
begin
select @start = @location +1
select @location = charindex(',',@str,@start)
select @next [email==@next]=@next[/email] +1
end
if @location =0 select @location =len(@str)+1
select @str_return = substring(@str,@start,@location-@start)
if (@index <> @next ) select @str_return = ''
return @str_return
end
2.自定义decode函数
create function dbo.decode(@col_name varchar(100),@val varchar(1000))
returns varchar(1000)
as
begin
declare @Ind int
declare @i int
declare @Res varchar(1000)
set @Ind=0
set @i=1
set @Res=''
set @Ind=len(@val)-len(replace(@val,',',''))+1
Tab_loop:
if @i<@Ind
begin
if dbo.getstrofindex(@val,@i)=@col_name
begin
set @Res=dbo.getstrofindex(@val,@i+1)
end
else
begin
set @i=@i+2
goto Tab_loop
end
end
else
begin
if @Res=''
begin
set @Res=dbo.getstrofindex(@val,@Ind)
end
end
return @Res
end
3.测试
表名cs1
no xb xm
1 男 张三
2 男 李四
3 女 张三
4 NULL 李四
select *,dbo.decode(no,'1,a,2,b,c') from cs1 -------no字段,为1显示a,为2显示b,否则显示c
no xb xm val
1 男 张三 a
2 男 李四 b
3 女 张三 c
4 NULL 李四 c
select *,dbo.decode(xb,'男,M,女,W,N') as val from cs1 -------------xb字段,为男显示M,为女显示W,否则显示N
no xb xm val
1 男 张三 M
2 男 李四 M
3 女 张三 W
4 NULL 李四 N
3. sqlserver里能用decode函数
不能,decode是Oracle里的内置函数,sqlserver里没有这个函数
4. SQL 如何不同列 显示不同条件查询的结果
select a.name,money1,money2 from
(
select name,sum(money) as money1
from table
where idate>1
) a
innser join (select name,sum(money) as money2
from table
where idate<1
) b on a.name=b,name