当前位置: 代码迷 >> SQL >> T-SQL(SQL Sever) 容易语句实例
  详细解决方案

T-SQL(SQL Sever) 容易语句实例

热度:33   发布时间:2016-05-05 12:18:31.0
T-SQL(SQL Sever) 简单语句实例

说明

此部分只注重语句的语法,使用场景和合理性不考虑在内。

此例子是主要是对一个货物表的价格进行操作。


创建表

//创建表create table goods(	gid int primary key,	gname varchar(10),    gprice float)


插入数据

//插入数据insert into goods values(1,'apple',15)insert into goods values(2,'banana',10)insert into goods values(3,'orange',5)


查询数据

select * from goods
查询价格上调 50% 的价格
select gname,gprice,gprice*1.5 as riceprice from goods

定义函数

此函数的作用很简单, 就是和上面价格上调的功能类似。根据上调比例计算新价格

create function riceprice(@price float,@ratio float)   returns float as  begin  declare @newprice float  set @newprice = @[email protected]  return(@newprice);  end
 调用这个函数:

select gname,gprice,dbo.riceprice(gprice,1.4) as riceprice from goods


定义触发器

作用很简单,在insert 新的货物后,打印货品价格+1 后的价格

create trigger ricepricetrigger   on goods for insertas  declare @id int,@price float  select @id=gid,@price =gprice+1  from inserted  print @price
在执行insert 语句之后会执行
insert into goods values(4,'pear',20)


定义存储过程

作用打印所有价格的汇总:

create proc ricepriceproc  @ratio float,  @totalprice float outputas  select @totalprice = sum([email protected]) from goods

调用如下:

begindeclare @tprice floatexec ricepriceproc 1.2,@tprice outputprint @tpriceend 



  相关解决方案