MSSQLSERVER数据库-存储过程(二)
sage = @age;
--不缓存在存储过程
use myschool;
create procedure proc_recompileStudent
with recompile
as
select * from student
exec proc_recompileStudent
--
加密的存储过程
create procedure proc_encrptStudent
with encryption
as
select * from student;
exec proc_recompileStudent
存储过程返回值的方式
1、返回数字类型的存储过程(还没有想到返回字符串的方法)
IF exists(select * from sys.objects where name='proc_getScore0')
drop procedure proc_getScore0
GO
create procedure proc_getScore0
(
@id int
)
AS
BEGIN
declare @score int
select @score=english from Score where id=@id
IF(@score>60)
return 0
ELSE
return 1
END
--测试调用返回数字的存储过程
declare @t int
declare @t int
EXEC @t = proc_getScore0 2
select @t;
--这里我遇到一个小问题,如果返回值是字符串,接收的时候declare @t nvarchar也出错,那该怎么做?
--暂时没有想到
2、返回变量的存储过程
IF exists(select * from sys.objects where name='proc_getScore')
drop procedure proc_getScore
GO www.2cto.com
CREATE PROCEDURE proc_getScore
@id int,
@result varchar(50) output
AS
BEGIN
declare @score int
select @score=english from Score where id=@id
IF(@score>60)
set @result='及格'
ELSE
set @result='不及格'
END
GO
--测试一
declare @id int
declare @temp varchar(50)
set @id=3
exec proc_getScore @id,@temp output
select @temp
最后一个例子,用C#来调用具有返回值的存储过程,这里我通过调用返回变量类型的存储过程来做测试。测试在控件台下进行,以下写了两种方法,第二种更好,代码如下:
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.SqlClient;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
//方法一
//using (SqlConnection conn = new SqlConnection("server=.;database=myschool;uid=sa;pwd=123456"))
//{
// conn.Open();
// using (SqlCommand cmd = new SqlCommand("proc_getScore", conn))
// {
// cmd.CommandType = CommandType.StoredProcedure;
// cmd.Parameters.AddWithValue("@id", 2);
// SqlParameter sp = cmd.Parameters.Add("@result", SqlDbType.VarChar, 50); www.2cto.com
// sp.Direction = ParameterDirection.Output;
// cmd.ExecuteNonQuery();
// Console.Write(sp.Value);
// }
//}
//方法二
using (SqlConnection conn = new SqlConnection("server=.;database=myschool;uid=sa;pwd=123456"))
{
conn.Open();
using (SqlCommand cmd = new SqlCommand("proc_getScore", conn))
{
cmd.CommandType = CommandType.StoredProcedure;
SqlParameter[] paras = {
new SqlParameter("@id",SqlDbType.Int),
new SqlParameter("@result",SqlDbType.NVarChar,50)
};
paras[0].Value = 2;
paras[1].Direction = ParameterDirection.Output;
cmd.Parameters.AddRange(paras);
cmd.ExecuteNonQuery();
Console.Write(paras[1].Value);
} www.2cto.com
}
Console.ReadLine();
}
}
}
作者 春晓