我使用C#将一些值插入SQL Server表中。实际上我想插入值并返回' ID'最后插入的记录。我使用以下代码:
string name = txt_name.Text.Trim();
string gender = Gender.Text.Trim();
string citizen = Citizen.Text.Trim();
int IdNo = Convert.ToInt32(idnumber.Text);
BUSSINESSACCESS.SENDMESSAGES send = new BUSSINESSACCESS.SENDMESSAGES();
DataSet dt = send.insertvoucher(name, gender, citizen, IdNo);
业务层
public DataSet insertvoucher(string name, string gender, string citizen, int IdNo)
{
SqlParameter[] par = {
new SqlParameter("@Name", name),
new SqlParameter("@Citizen", citizen),
new SqlParameter("@Emiratesidno", IdNo),
new SqlParameter("@gender", gender),
};
var rowCount = SHJCSQLHELPER.ExecuteScalar(CONNECTIONSTRING, CommandType.StoredProcedure, "[INSERTVOUCHER]", par);
return rowCount;
// return SHJCSQLHELPER.ExecuteDataset(CONNECTIONSTRING, CommandType.StoredProcedure, "[INSERTVOUCHER]", par);
//string mn = "";
}
存储过程
-- Insert statements for procedure here
Insert into Usertable(Name, Citizen, Emiratesidno, gender)
values (@Name, @Citizen, @Emiratesidno, @gender)
SELECT scope_identity() AS int
我在变量rowcount中获取值但是我无法返回变量rowcount,因为它说
无法隐式转换类型'对象'到' system.data.dataset'
答案 0 :(得分:3)
您没有投射,您将列名称别名为int,
使用:Private Sub cmdSearch_Click()
Dim varItem As Variant
Dim strSearch As String
Dim Task As String
For Each varItem In Me!GroupList.ItemsSelected
strSearch = strSearch & "," & Me!GroupList.ItemData(varItem)
Next varItem
MsgBox (strSearch)
If Len(strSearch) = 0 Then
Task = "select * from Group_Affiliations"
Else
strSearch = Right(strSearch, Len(strSearch) - 1)
Task = "select * from Group_Affiliations where ([Group Affiliations] in (" & strSearch & "))"
End If
DoCmd.ApplyFilter Task
End Sub
SELECT CAST(scope_identity() AS int)
是盒装整数。更改return语句和返回类型。例如:
return(int)rowCount;
这是您所需的身份证。
答案 1 :(得分:1)
使用(Int32)
var rowCount = (Int32)SHJCSQLHELPER.ExecuteScalar(CONNECTIONSTRING, CommandType.StoredProcedure, "[INSERTVOUCHER]", par);
scope_identity()
默认返回INT
,无需投射。
您还可以设置存储过程以使用OUT参数并将Scope_Identity()
指定给它并调整您的C#以使用此
<强>校正强>
scope_identity()
会返回decimal
而非int
。如果您的identity
列是int
,则转化是自动的,不需要转换。
由于我在大多数存储过程中使用output
参数而未返回select
语句