执行Insert命令并使用C#在SQL Server中返回插入的Id

时间:2017-04-17 15:20:40

标签: c# sql-server winforms stored-procedures

我使用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'

2 个答案:

答案 0 :(得分:3)

  1. 您没有投射,您将列名称别名为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

  2. SELECT CAST(scope_identity() AS int)是盒装整数。更改return语句和返回类型。例如:

  3.   

    return(int)rowCount;

    这是您所需的身份证。

    参考:SqlCommand.ExecuteScalar MSDN

答案 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语句

,因此我有点生疏