server2005 存储过程

 

测试表结构 

CREATE TABLE [BASE_ADMIN_USER](

[userID] [int] NOT NULL PRIMARY KEY ,

[userName] [varchar](16)   NOT NULL,

[password] [varchar](16)   NOT NULL,

[userType] [smallint] NOT NULL,

[realName] [varchar](32)   NULL,

[userEmail] [varchar](32)   NULL,

[pwdTime] [smalldatetime] NULL,

[emailSubscribe] [varchar](32)  NULL,

扫描二维码关注公众号,回复: 1288954 查看本文章

[status] [smallint] NOT NULL,

[mender] [int] NOT NULL,

[modifyTime] [smalldatetime] NOT NULL,

[ciosing] [smallint] NULL,

[age] [int] NULL 

)

 

 

一、定义变量(基础学习)

declare 

--1 声明两个变量

@a int ,   @name varchar(10) ,@age int ,@userID int ,@selName varchar(10)

--给两个变量赋值

set @a=5 

set@name='set名字直接赋值'

--select数据赋值

select @age=isnull(age,0) ,@userID =userID  from  dbo.BASE_ADMIN_USER 

select @selName='select名字赋值'

 

--int 转换成字符串  与字符串连接   字符串打印

print cast(@a as varchar(10))   +'   '+ @name

print cast(@age as varchar(10)) +'   '+ cast(@userID  as varchar(10))

print @name  +'    '+@selName

--也可以这样输出

--select @age

 

 

 

二临时表的应用 

insert into [BASE_ADMIN_USER_temp]  select * from   dbo.BASE_ADMIN_USER

 

--添加一列,为int型自增长子段 

alter table #t add [myid] int NOT NULL IDENTITY(1,1) 

--添加一列,默认填充全球唯一标识 

alter table #t add [myid1] uniqueidentifier NOT NULL default(newid()) 

 

 

 

三 循环使用 

--声明变量

declare @a int 

declare @sum  int 

--设置初始值

set @a=1

set @sum=0

--循环开始

while @a<10

begin 

set @sum = @sum + @a

set @a=@a+1

end 

-- 打印

print @sum

 

 

四 case when then 使用

declare @today int

declare @week nvarchar(3) 

set @today=3 

set @week= case

   when @today=1 then '星期一'

   when @today=2 then '星期二'

   when @today=3 then '星期三'

   when @today=4 then '星期四'

   when @today=5 then '星期五'

   when @today=6 then '星期六'

   when @today=7 then '星期日'

   else '值错误'

end

print @week

 

五 游标使用

declare @userID int 

declare @userName varchar(10)  

 

--定义一个游标 

declare user_cur cursor for select userID,userName  from BASE_ADMIN_USER 

--打开游标 

open user_cur 

while @@fetch_status=0 

begin

--读取游标 

   fetch next from user_cur into  @userID,@userName 

   print cast(@userID as varchar(10) ) +'    '+@userName 

   --print @Login 

end

close user_cur 

--摧毁游标 

deallocate user_cur

 

 

 

六 存储过程的创建与执行

  删除存储过程

  Drop procedure [Proc_open_test]

 

--创建带output参数的存储过程 

CREATE PROCEDURE PR_Sum 

   @a int, 

   @b int, 

   @sum int output

AS

BEGIN

   set @sum=@a+@b 

END

 

--创建Return返回值存储过程 

CREATE PROCEDURE PR_Sum2 

   @a int, 

   @b int

AS

BEGIN

   Return @a+@b 

END

     

--执行存储过程获取output型返回值 

declare @mysum int

execute PR_Sum 1,2,@mysum output

print @mysum 

 

--执行存储过程获取Return型返回值 

declare @mysum2 int

execute @mysum2= PR_Sum2 1,2 

 

print @mysum2  打印数据到控制台

select @exeRtn;  打印数据到表格 

 

猜你喜欢

转载自username2.iteye.com/blog/1894825
今日推荐