SqlServer数据库存储过程、函数、触发器10题及答案

1. 编写存储过程根据员工号查询员工全部信息
create procedure getEmoloyee
@id nvarchar(64)
as
select * from employees where EMPLOYEE_ID=@id
go
2.编写存储过程根据员工号修改其工资,员工号和新工资都以参数传递
create procedure getEmoloyee
@id nvarchar(64),
@salary numeric(8,2)
as
update employees set SALARY=@salary where EMPLOYEE_ID=@id
go
3. 编写自定义函数tax根据工资计算税金,按阶段式计税法,3000(含)以下不收税;3000以上到5000部分收3%的税;5000以上到10000部分收8%的税,10000以上到30000部分收20%的税;30000以上部分收40%的税
create function tax(@salary numeric(8,2))
returns int
as
begin
declare @myresult int
if @salary<3000
return 0
else if @salary>=3000 and @salary<5000
set @myresult=@salary0.03
else if @salary>=5000 and @salary<10000
set @myresult=@salary
0.08
else if @salary>=10000 and @salary<30000
set @myresult=@salary0.2
else if @salary>=30000
set @myresult=@salary
0.4
return (@myresult)
end
4. 编写存储过程根据员工号查询其工资并利用上题的tax函数计算税金
create procedure getEmoloyee
@id nvarchar(64)
as
select SALARY-[dbo].tax(SALARY) from employees where EMPLOYEE_ID=@id
go
5.创建一个存储过程,以员工号为参数,修改该员工的工资。若该员工属于10号部门,则工资增加150;若属于20号部门,则工资增加200;若属于30号部门,则工资增加250;若属于其他部门,则增加300。
create procedure setSALARY
@id nvarchar(64)
as
declare @manid int
set @manid=(select MANAGER_ID from employees where EMPLOYEE_ID=@id)
if @manid=10
update employees set SALARY=SALARY+150 where EMPLOYEE_ID=@id
else if @manid=20
update employees set SALARY=SALARY+200 where EMPLOYEE_ID=@id
else if @manid=30
update employees set SALARY=SALARY+250 where EMPLOYEE_ID=@id
else
update employees set SALARY=SALARY+300 where EMPLOYEE_ID=@id
go
6. 创建一个存储过程,以员工号为参数,返回该员工的工作年限(以参数形式返回)
create procedure Date
@id nvarchar(64)
as
declare @output int
set @output=(select datediff(year,HIRE_DATE,getdate()) from employees where EMPLOYEE_ID=@id)
return @output
go
7. 创建一个函数,以部门号为参数,返回该部门的平均工资
create function AvgSalary(@id int)
returns int
as
begin
declare @myresult int
set @myresult=(select AVG(SALARY) from employees where DEPARTMENT_ID=@id)
return (@myresult)
end
8. 创建一个存储过程,以两个整数为参数,输出工资排序在两个参数之间的员工信息
create procedure minmax
@min int,
@max int
as
select top (@min) * from (select top (@max) * from employees order by SALARY desc) t order by SALARY
go
9. 编写一个触发器,若在周六周日向员工表插入或修改数据,则拒绝,并提示“今天休息”
create trigger test on employees after insert,update
as
begin
declare @week int
set @week=(select @@DATEFIRST)
if @week=6 or @week=7
begin
raiserror(‘今天休息’,16,1);
rollback tran
end
end
10. 编写一个触发器,每当员工表数据被更改时,旧数据会自动写入emp_history表(与employees表结构一样),然后新数据再写入employees表
create trigger test on employees after insert,update
as
begin
declare @week int
set @week=(select @@DATEFIRST)
if @week=6 or @week=7
begin
if not exists(select * from sysobjects where name=‘emp_history’)
begin
truncate table emp_history
insert into emp_history select * from employees
end
else
begin
truncate table emp_history
insert into emp_history select * from employees
end
end
end

如有写的不对的地方,还望大家评论区指正

你可能感兴趣的:(原创,数据库,数据库,sqlserver,database,存储过程,触发器)