- 牛云
-
解决思想: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
- LuckySXyd
-
create function uf_decode(@argu varchar(999))
returns integer
as
begin
--对@argu进行分解
--使用动态SQL组织CASE语法结构
end
引用uf_decode时把参数以一个字符串的形式传入﹐
你再试试﹐如果不行﹐晚上我帮你写。