函数

分类:

--(1)系统函数
--(2)自定义函数 --->1.标量值函数(返回单个值),2.表值函数(返回查询结果)

基本使用:
有返无参

--编写一个函数求该银行的金额总和
create function GetSumCardMoney()		--定义有返无参的函数
returns money 	--返回值类型
as
begin
	declare @AllMOney money
	select @AllMOney = (select SUM(CardMoney) from BankCard)
	return @AllMOney	--返回
end

--函数调用
select dbo.GetSumCardMoney()

有返有参

create function GetNameById(@AccountId int)		--定义有返有参的函数
returns  varchar(20)
as
begin
	declare @RealName varchar(20)
	select @RealName = (select RealName from AccountInfo where AccountId = @AccountId)
	return @RealName
end
go

drop function GetNameById  --删除函数

--函数调用
print dbo.GetNameById(2)

表值函数

--通过函数实现,传递开始时间和结束时间,返回交易记录(存钱取钱)
--交易记录中包含 真实姓名,卡号,存钱金额,取钱金额,交易时间

--方案一:
create function GetExchangeByTime(@StartTime varchar(30),@EndTime varchar(30))
returns @ExchangeTable table
(
	RealName varchar(30),  --真实姓名
	CardNo varchar(30),    --卡号
	MoneyInBank money,     --存钱金额
	MoneyOutBank money,    --取钱金额
	ExchangeTime smalldatetime  --交易时间
)
as
begin
	insert into @ExchangeTable
	select AccountInfo.RealName,CardExchange.CardNo,CardExchange.MoneyInBank,
	CardExchange.MoneyOutBank,CardExchange.ExchangeTime from CardExchange
	left join BankCard on CardExchange.CardNo = BankCard.CardNo
	left join AccountInfo on BankCard.AccountId = AccountInfo.AccountId
	where CardExchange.ExchangeTime between @StartTime+' 00:00:00' and @EndTime+' 23:59:59'
	return
end

--函数调用
select * from GetExchangeByTime('2018-6-1','2018-7-1')


--方案二:(只能return 和sql语句)
create function GetExchangeByTime(@StartTime varchar(30),@EndTime varchar(30))
returns table
as
	return
	select AccountInfo.RealName,CardExchange.CardNo,CardExchange.MoneyInBank,
	CardExchange.MoneyOutBank,CardExchange.ExchangeTime from CardExchange
	left join BankCard on CardExchange.CardNo = BankCard.CardNo
	left join AccountInfo on BankCard.AccountId = AccountInfo.AccountId
	where CardExchange.ExchangeTime between @StartTime+' 00:00:00' and @EndTime+' 23:59:59'

上一篇:mysql数据库按照varchar字符串类型排序


下一篇:运行工作流项目​​