SQL Server 2008 存储过程示例

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了SQL Server 2008 存储过程示例相关的知识,希望对你有一定的参考价值。

出处:http://www.jb51.net/article/54730.htm

--有输入参数的存储过程--
create proc GetComment
(@commentid int)
as
select * from Comment where [email protected]
 
调用方式:exec GetComment 3
  
--有输入与输出参数的存储过程--
create proc GetCommentCount
@newsid int,
@count int output
as
select @count=count(*) from Comment where [email protected]
 
调用方式:
declare @cnt int
exec GetCommentCount 1,@cnt  output
print @cnt
 
--返回单个值的函数--
create function MyFunction
(@newsid int)
returns int
as
begin
declare @count int
select @count=count(*) from Comment where [email protected]
return @count
end
 
调用方式:
declare @cnt int
exec @cnt = MyFunction 1
print @cnt
 
--返回值为表的函数--
Create function GetFunctionTable
(@newsid int)
returns table
as
return
(select * from Comment where [email protected])
go
  
调用方式:
select * from GetFunctionTable(2)
 

CREATE proc func_withconditions
(
 @firstName varchar(20),
 @lastName varchar(20)
)
AS
begin
    declare @sql varchar(500)
    set @sql = ‘select * from employee where 1=1  ‘
    if(@firstName is not null)
          set @sql = @sql+‘ and first_name=‘+‘‘‘‘[email protected]+‘‘‘‘
    if(@lastName <> ‘ ‘ and @lastName is not null)
          set @sql = @sql+‘ and last_name=‘+‘‘‘‘[email protected]+‘‘‘‘
    exec(@sql)
end
GO
 
调用方式:
exec func_withconditions ‘ahg‘,‘‘
exec func_withconditions ‘ahg‘,NULL
exec func_withconditions NULL,‘jhg‘
 
 
 

以上是关于SQL Server 2008 存储过程示例的主要内容,如果未能解决你的问题,请参考以下文章

SQL Server 2008之存储过程的设计和实现

将用户定义表中的日期值传递给 SQL Server 2008 存储过程

如何在SQL Server 2008下轻松调试T-SQL语句和存储过程

从 Sql Server 2008 执行 oracle 存储过程

SQL SERVER 2008 存储过程传表参数

如何自动导出 SQL Server 2008 版本的存储过程