Multi Statement Function

---Hiç olmayan tablo yapısını geri döndürebiliriz.

/*
		REZID		REZNO		UCRET		BIRIM
		123			123ER		12			TL
		345			2545AAA	23	23			USD
		384			DFDASSD		784			EURO
		
		SONUÇ:
		
		REZNO		TL			USD			EURO
		123			12			-			-
		345			-			23			-
		384			-			-			784
*/
--İlkönce tablo oluşturalım
create table Rez
(
	RezID int Primary key identity(1,1),
	Ucret decimal(5,2),
	Birim char(4)
)

--değerleri girelim
insert into Rez values(12.34,'TL')
insert into Rez values(15.27,'USD')
insert into Rez values(10.05,'EURO')

--ŞİMDİ MULTI STATEMENT FUNCTION YARARINI GÖRELIM
create function udf_Tablocu()
returns @tablo table
(
	RezID int,
	TL varchar(8),
	EURO varchar(8),
	USD varchar(8)
)
as
begin
	declare @rezID int
	declare @birim char(4)
	declare @tl varchar(8),@usd varchar(8), @euro varchar(8), @ucret varchar(8)
	
	declare @id int 
	set @id=1
	
	declare @maxID int
	select @maxID=max(RezID) from Rez
	
	while @id<=@maxID
	begin
		select @rezID=RezID,@birim=Birim,@ucret=cast(Ucret as varchar(8))
		from Rez
		where RezID=@id
		
		if ltrim(rtrim(@birim)) is not null
		begin
			if @birim='TL'
			begin
				set @tl=@ucret
				set @usd='-'
				set @euro='-'
			end
			else if ltrim(rtrim(@birim))='USD'
			begin
				set @tl='-'
				set @usd=@ucret
				set @euro='-'
			end
			else if ltrim(rtrim(@birim))='EURO'
			begin
				set @tl='-'
				set @usd='-'
				set @euro=@ucret
			end
			insert into @tablo
			values(@rezID,@tl,@euro,@usd)
		end
		set @id=@id+1
	end
	return
end

select * from dbo.udf_Tablocu()