首先,在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 ”