1: use [MyDemo]
2: go
3: alter FUNCTION Dep_Salaries1
5: @empid int
7: RETURNS @table table
9: Department int,
10: Salary_Max int,
11: Salary_Min int
12: )
13: AS
14: BEGIN
15: declare @Department int = (select S.deptid from Employees s where s.empid=@empid)
16: insert into @table
17: SELECT S.deptid , max (Salary) , MIN(Salary) FROM Employees s inner join Departments T ON S.deptid =T.deptid group by S.deptid having S.deptid =@Department
18: RETURN
19: END
20: GO
b. 使用TVF的低性能T-SQL:
1: alter procedure Unperformant_SP1
2: @empid int
3: as
4: begin
5: select T.deptid as department_name , s.* from Dep_Salaries1 (@empid )S inner join Departments T ON S.Department =T.deptid
6: end
c. 使用临时表代替TVF:
1: go
2: alter procedure Performant_SP1
3: @empid int
4: as
5: begin
6: create table #table
8: Department int,
9: Salary_Max int,
10: Salary_Min int
11: )
12: create clustered index #table_index1 on #table (Department)
13: insert into #table select * from Dep_Salaries1 (@empid )
14: select T.deptid as department_name , s.* from #table S inner join Departments T ON S.Department =T.deptid
15: end
1: use [Workshops]
2: go
3: create FUNCTION Salary_Tax
5: @empid int
7: RETURNS float
8: AS
9: BEGIN
10: declare @salary int = (select (S.salary-100) from Employees s where s.empid=@empid)
11: RETURN @salary
12: END
13: GO
14: --性能低些的标量函数
15: Select empid ,dbo.Salary_Tax (empid) as 'SalaryWithTax' from Employees
b. 使用临时表替换标量函数:
1: Create Table #temp (Empid int primary key clustered , Salary_Tax float)
2: Create nonclustered index #temp_Index1 on #temp (Empid ) include (Salary_Tax )
3: insert into #temp select Empid ,(Salary-100) as salary_Tax from Employees
4: select * from #temp
c. 使用持久化确定的计算列:
1: ALTER TABLE dbo.Employees ADD Salary_Tax AS Salary-100 PERSISTED
2: Create nonclustered index Employees_Index1 on Employees (Empid, Salary_Tax )
3: select empid ,Salary_Tax from Employees
d. 使用计划工作代替标量函数:
1: ALTER TABLE dbo.Employees ADD Salary_Tax1 float, update_flag bit
2: ALTER TABLE dbo.Employees ADD CONSTRAINT DF_Employees_update_flag DEFAULT 0 FOR update_flag
3: Schedule the below DML update by an appropriate frequency according to your workload
4: Update Employees set Salary_Tax1=Salary-100 WHERE UPDATE_Flag=0
5: Then you can include the below select query within your stored procedure.
6: select empid , Salary_Tax1 from Employees