sql 学习笔记之:存储过程和用户自定义函数
2009-05-22 11:33
381 查看
sql 学习笔记之:存储过程和用户自定义函数
2009-05-21 13:28
2009-05-21 13:28
一:存储过程的简单创建,修改与删除 1.创建简单的存储过程 use AdventureWorks go create proc spEmployee as select * from HumanResources.Employee 执行上面的代码就创建了一个存储过程 如果想运行这个存储过程 可以直接执行exec spEmployee这个语句 2.更改存储过程 ALTER proc [dbo].[spEmployee] as select top 13 * from HumanResources.Employee 3.删除存储过程 drop proc dbo.spEmployee 二:存储过程的输入参数和输出参数 1.有输入参数的存储过程 use AdventureWorks go create proc spEmployee @LastName nvarchar(50) = null as if @LastName is null select top 13 * from HumanResources.Employee else select top 10 * from HumanResources.Employee 查看该存储过程的结果可以用 exec spEmployee '123' 或直接exec spEmployee 存储过程的重载... 2.有输出参数的存储过程 use AdventureWorks go alter proc spEmployee @LastName nvarchar(50) = null output as if @LastName is null begin print 'null' return '123' end else begin print @LastName return '456' end 看第一个测试该存储过程的语句 declare @myval nvarchar(50) exec @myval = spEmployee @myval output print @myval 输出null 123 第二个测试该存储过程的语句 declare @myval nvarchar(50) set @myval = 'xland' exec @myval = spEmployee @myval output print @myval 输出xland 456 三:用户定义函数 1.返回标量值的用户定义函数 先做一个简单的日期处理函数 把长日期缩短成短日期 Create function dbo.DayOnly(@date datetime) returns varchar(12) as begin return convert(varchar(12),@date,101) end 为了测试上面的函数先做个脚本 use Accounting declare @counter int set @counter = 1 while @counter <= 10 begin insert into Orders values(1,dateadd(mi,@counter,getdate()),1) set @counter = @counter +1 end 然后检索这个脚本 新插入的数据记录 use Accounting select * from orders where dbo.DayOnly(date1) = dbo.DayOnly(getdate()) 2.返回表的用户定义函数 先看例子 use AdventureWorks go create function dbo.fnContactSearch(@LastName nvarchar(50)) returns table as return (select * from Person.Contact where LastName like @LastName+'%') 执行这个例子 use AdventureWorks select * from fnContactSearch('Ad') 3.综合例子:返回表,有输入参数 use xland go create function dbo.funGetMytable (@id as int) returns @allrows table ( id int not null, title nvarchar(max) null ) as begin insert into @allrows select id,title from mytable where id = @id return end go 执行这个例子 select * from funGetMytable(1) |
相关文章推荐
- SQL存储过程学习笔记(一)
- SQL 学习笔记<六> 存储过程细看
- PL/SQL学习笔记_03_存储函数与存储过程
- 存储过程学习笔记三---T-SQL基本知识
- SQL存储过程学习笔记(一)
- DB2 SQL存储过程学习笔记
- DB2 SQL存储过程学习笔记
- 提高DB2数据库SQL存储过程性能学习笔记
- SQL 学习笔记<六> MySQL存储过程基础
- 转载:提高DB2数据库SQL存储过程性能学习笔记
- sql学习笔记--存储过程
- sql存储过程学习实例
- Oracle 学习笔记13 —— 存储过程
- 存储过程学习笔记(二) 返回值
- Mysql存储过程学习笔记--变量、参数、注释
- PL/SQL学习笔记-过程
- SQL Server 2005存储过程学习笔记——引子
- MySQL存储过程学习笔记
- Java学习笔记之数据库(触发器、事物、索引、投影和除、视图、存储过程和函数 )含各种链)___ 一直补充
- SQL SERVER 存储过程学习笔记