.net下调用sqlserver存储过程的小例子
程序员文章站
2024-03-02 18:06:22
首先,在sqlserver中创建存储过程,在调用时分为有参数和没有参数两种情况,先就简单的没有参数的情况简要的介绍: 假设存储过程如下: 复制代码 代码如下: ...
首先,在sqlserver中创建存储过程,在调用时分为有参数和没有参数两种情况,先就简单的没有参数的情况简要的介绍:
假设存储过程如下:
create proc selectall
as
select * from studentinf
则此sp的调用如下:
sqlcommand selectcmd = new sqlcommand(“selectall”, conn);
//conn 为sqlconnection
selectcmd.commandtype = commandtype.storedprocedure;
如果需要将结果集加到某个dataadapter上,则可如下:
sqldataadapter studa = new sqldataadapter();
studa.selectcommand = selectcmd;
如果有参数:create proc andselect
@studentid varchar(10),
@studentname varchar(10),
as
select * from studentinf where studentid = @studentid and studentname = @studentname
则参数可以如下添加:
selectcmd.parameters.add(“@studentid”, sqldbtype.nvarchar, 10);
selectcmd.parameters.add(“@studentname”, sqldbtype.nvarchar, 10);
如果只有一个参数,也可以这样赋值:
sqlparameters onepara = selectcmd.parameters.add(“@studentid”, sqldbtype.nvarchar, 10);
onepara.value = “ a string ”
假设存储过程如下:
复制代码 代码如下:
create proc selectall
as
select * from studentinf
则此sp的调用如下:
sqlcommand selectcmd = new sqlcommand(“selectall”, conn);
//conn 为sqlconnection
selectcmd.commandtype = commandtype.storedprocedure;
如果需要将结果集加到某个dataadapter上,则可如下:
sqldataadapter studa = new sqldataadapter();
studa.selectcommand = selectcmd;
如果有参数:create proc andselect
@studentid varchar(10),
@studentname varchar(10),
as
select * from studentinf where studentid = @studentid and studentname = @studentname
则参数可以如下添加:
selectcmd.parameters.add(“@studentid”, sqldbtype.nvarchar, 10);
selectcmd.parameters.add(“@studentname”, sqldbtype.nvarchar, 10);
如果只有一个参数,也可以这样赋值:
sqlparameters onepara = selectcmd.parameters.add(“@studentid”, sqldbtype.nvarchar, 10);
onepara.value = “ a string ”