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