SQL存储过程与自定义函数实例

存储过程

1、create PROCEDURE Sp_Conn_Sort
(
@tblName   varchar(255),       -- 表名

@strGetFields varchar(1000) = '*',  -- 需要返回的列

)

as

 declare @strSQL   varchar(5000)       -- 主语句,声明变量

  begin

          set @strSQL='select count(*) as Total from ' + @tblName + ' where '+@strWhere
  end

  exec(@strSQL) --执行SQL相当于 select count(*) as Total from tblName

 

2、调用存储过程

  exec Sp_Conn_Sort '',''   不能加括号    或者 exec Sp_Conn_Sort @tblName='',@strGetFields=''

 

自定义函数

1、create function addEx
(@a int=1,
 @b int=1
)
returns int --注意这里与存储过程的区别
AS
begin
   return  @a+@b
end

2、调用函数

select dbo.addEx(2,2)  --这里要加上dbo.区别与内置函数

posted @ 2010-09-30 16:59  知足常乐(Mr.Zhang)  阅读(329)  评论(0)    收藏  举报