一、存储过程
1、表的结构
create Database StudentInfo
use StudentInfo
Create table Student(
Id int PRIMARY key IDENTITY(1,1),
StuNo Nvarchar(50) unique,
Name VARCHAR(200),
)
INSERT INTO Student VALUES('001','张三');
INSERT INTO Student VALUES('002','李四');
INSERT INTO Student VALUES('003','桃五');
INSERT INTO Student VALUES('004','王六');
Create table Course(
Id int PRIMARY key IDENTITY(1,1),
_Id int,
Score VARCHAR(200),
)
INSERT INTO Course VALUES(2,'60');
INSERT INTO Course VALUES(3,'70');
INSERT INTO Course VALUES(4,'80');
[SQL]INSERT INTO Student VALUES('','001','张三')
[Err] 23000 - [SQL Server]仅当使用了列列表并且 IDENTITY_INSERT 为 ON 时,才能为表'Student'中的标识列指定显式值。
则去掉给主键的值则应为:
INSERT INTO Student VALUES('001','张三')
2、无参数存储过程
--创建名为 GetStuCou 的无参数存储过程
create procedure GetStuCou
as
begin
select *
from Student s
left join Course c on s.Id=c._Id
end
--执行名为 GetStuCou 的无参数存储过程
execute GetStuCou
3、有返回值的存储过程(插入数据用的数据库是变得才行 这个例子是固定的执行的时候意义不大)
--创建名为 GetStuCou_Re 的有返回值的存储过程
create procedure GetStuCou_Re
as
begin
INSERT INTO Course VALUES(1,'80');
return SCOPE_IDENTITY(); -- 返回为当前表插入数据最后生成的标识值。
end
--执行名为 GetStuCou 的有返回值的存储过程
execute GetStuCou_Re
4、有输入、输出参数的存储过程:
--创建名为 GetStuCou_In 的有输入参数的存储过程
create procedure GetStuCou_In
@StuNo nvarchar(64)='001' --设置默认值
as
begin
select * from Student where StuNo=@StuNo
end
--执行名为 GetStuCou_In 的有输入参数的存储过程(不传参数,即使用默认值)
execute GetStuCou_In
--执行名为 GetStuCou_In 的有输入参数的存储过程(传入参数)
execute GetStuCou_In '004'
5、C#调用存储过程
string strsql = "Data Source=localhost;Initial Catalog=StudentInfo;Integrated Security=True";//数据库链接字符串
string sql = "GetStuCou_In";//要调用的存储过程名
SqlConnection conStr = new SqlConnection(strsql);//SQL数据库连接对象,以数据库链接字符串为参数
SqlCommand comStr = new SqlCommand(sql, conStr);//SQL语句执行对象,第一个参数是要执行的语句,第二个是数据库连接对象
comStr.CommandType = CommandType.StoredProcedure;//因为要使用的是存储过程,所以设置执行类型为存储过程
//依次设定存储过程的参数
comStr.Parameters.Add("@StuNo", SqlDbType.Text).Value = "004";//这里的@StuNo要和定义的参数名字一致
conStr.Open();//打开数据库连接
//MessageBox.Show(comStr.ExecuteNonQuery().ToString());//执行存储过程 返回影响函数 -1
SqlDataAdapter SqlDataAdapter1 = new SqlDataAdapter(comStr);
DataTable DT = new DataTable();
SqlDataAdapter1.Fill(DT);
MessageBox.Show(DT.Rows[0][0].ToString());
conStr.Close();//关闭连接