如何分配变量?

时间:2016-07-15 08:46:27

标签: angularjs sql-server stored-procedures

我不知道如何将存储过程的值返回分配到web api中?如何传递变量througn angulrjs

我打电话给服务

var promisePost = crudService.candidatePost(Candidates);
            promisePost.then(function (pl) {
                alert("Sucessfully Inserted")

            }, function (err) {
                alert("NOt Inserted")
           });

我的app.js是

 MyApp.service('crudService', function ($http, RESOURCES) {
 this.candidatePost = function (Candidate) {
    var request = $http({
        method: "post",
        url: RESOURCES.baseUrl + "saveCandidate",
        data: Candidate
    });
    return request;
}

}); 我的控制器是

    [HttpPost]
    [Route("api/saveCandidate")]

    public HttpResponseMessage AddDetail(Candidate ct)
    {
        SqlConnection con = new SqlConnection(Constant.ConnectionString);
        SqlCommand cmd = new SqlCommand();
         int rowInserted = 0;

        try
        {

           cmd = new SqlCommand("sp_Insert_tblCandidate", con);
            con.Open();
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.Parameters.AddWithValue("@Name", ct.Name);
            cmd.Parameters.AddWithValue("@Gender", ct.Gender);
            cmd.Parameters.AddWithValue("@Dob", ct.Dob);
            cmd.Parameters.AddWithValue("@Mob", ct.Mob);
            cmd.Parameters.AddWithValue("@EntryDate", ct.EntryDate);
            cmd.Parameters.AddWithValue("@Note", ct.Note);
            cmd.Parameters.AddWithValue("@Emial", ct.Emial);
            cmd.Parameters.AddWithValue("@Address", ct.Address);
            rowInserted = cmd.ExecuteNonQuery();
              con.Close();
        }
        catch (Exception obj)
        {
            if (rowInserted != 1)
            {
                var message = obj.Message;// string.Format("Insertion Of Data is not Succefully Executed");
                HttpError err = new HttpError();
                 return Request.CreateResponse(HttpStatusCode.NotFound, err);

            }
        }
        finally
        {
            if (con.State == System.Data.ConnectionState.Open)
            {

                con.Close();
            }
        }
        var alertmessage = string.Format("Insertion Of Data is  Succefully Executed");
        return Request.CreateResponse(HttpStatusCode.OK, alertmessage);

    }

我的存储过程是

IF EXISTS ( SELECT * 
        FROM   sysobjects 
        WHERE  id = object_id(N'[dbo].[sp_Insert_tblCandidate]') 
               and OBJECTPROPERTY(id, N'IsProcedure') = 1 )
BEGIN
DROP PROCEDURE [dbo].[sp_Insert_tblCandidate]
END

GO
 Create procedure [dbo].[sp_Insert_tblCandidate]
  (@Name varchar(50) ,
  @Gender char(1),
  @dob varchar(25),
  @Mob varchar(15),
  @EntryDate varchar(50),
  @Note varchar(100),
  @Emial varchar(50),
  @Address varchar(50)
)As
Begin
INSERT INTO [dbo].[tblCandidate] VALUES (@Name,@Gender,@dob,@Mob,@EntryDate,@Note,@Emial,@Address);
SELECT SCOPE_IDENTITY() as CandidateId;
end
GO

我的存储过程目的是插入数据&返回上次插入的id。在这个表中id设置为auto increment.Anyone可以帮助我吗?

2 个答案:

答案 0 :(得分:0)

您将返回新的ID,因此您不应该使用

cmd.ExecuteNonQuery()

但可以处理返回值的东西。尝试将其更改为

 rowInserted = (int) cmd.ExecuteScalar();

此外,您现在正在检查rowInserted中的catch,这没有多大意义。

答案 1 :(得分:0)

您无法从ExecuteNonQuery()获取结果,因为它只返回您刚刚执行的查询所受影响的行数。

由于您要返回SCOPE_IDENTITY(),因此您可以使用ExecuteReader()ExecuteScalar()

rowInserted = (int)cmd.ExecuteScalar();

using(SqlDataReader rdr = cmd.ExecuteReader())
{
    while(rdr.Read())
    {
        rowInserted = Convert.ToInt32(rdr[0]);
    }
}

但在这种情况下使用SqlDataReader是不必要的。

另外,只是一个观察;在SCOPE_IDENTITY()@@IDENTITYIDENT_CURRENT之间进行选择时要小心。