2012-10-16 109 views
0

检索返回值我有一个存储过程,如下所示:从存储过程

CREATE PROCEDURE procTest 
    -- Add the parameters for the stored procedure here 
    @gameId int = NULL, 
    @memberID int = NULL, 
    @mediatorID int = NULL, 
    @id int OUTPUT 
AS 
BEGIN 
    -- SET NOCOUNT ON added to prevent extra result sets from 
    -- interfering with SELECT statements. 
    SET NOCOUNT ON; 

    -- Insert statements for procedure here 
    INSERT INTO tblSiteChallengeMember (gameId, creatorId, mediatorId, completed, dateAdded) VALUES (@gameId, @memberId, @mediatorID, 0, GETDATE()) 
END 
GO 

我需要返回的tblSiteChallengeMember的ID,但我不知道该怎么做。

我见过的例子'round about here,但恐怕:

SELECT TOP 1 @ProductName=PRODUCTNAME, @Quantity =quantity 
FROM Products P, [Order Details] OD, Orders O, Customers C 
WHERE C.CustomerID = @CustomerID 
AND C.CustomerID = O.CustomerID AND O.OrderID = OD.OrderID AND OD.ProductID = P.ProductID 

不会工作,由于单个用户可以输入多次,并且这些时间可能不是唯一的。

如何获取插入到我的ASP.net页面的最后一行的ID?


更新我的存储过程:

ALTER PROCEDURE [dbo].[procCreateChallengeMember] 
    -- Add the parameters for the stored procedure here 
    @gameId int = NULL, 
    @memberID int = NULL, 
    @mediatorID int = NULL, 
    @id int OUTPUT 
AS 
BEGIN 
    -- SET NOCOUNT ON added to prevent extra result sets from 
    -- interfering with SELECT statements. 
    SET NOCOUNT ON; 

    -- Insert statements for procedure here 
    INSERT INTO tblSiteChallengeMember (gameId, creatorId, mediatorId, completed, dateAdded) VALUES (@gameId, @memberId, @mediatorID, 0, GETDATE()) 

    SELECT @id = SCOPE_IDENTITY() 
END 

SQL表是:

GO 

/****** Object: Table [dbo].[tblSiteChallengeMember] Script Date: 10/17/2012 08:05:12 ******/ 
SET ANSI_NULLS ON 
GO 

SET QUOTED_IDENTIFIER ON 
GO 

CREATE TABLE [dbo].[tblSiteChallengeMember](
    [id] [int] IDENTITY(1,1) NOT NULL, 
    [gameId] [int] NULL, 
    [creatorId] [int] NOT NULL, 
    [mediatorId] [int] NULL, 
    [completed] [tinyint] NULL, 
    [dateAdded] [datetime] NULL, 
CONSTRAINT [PK__tblSiteD__3213E83F628FA481] PRIMARY KEY CLUSTERED 
(
    [id] ASC 
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] 
) ON [PRIMARY] 

GO 

aspx.cs是:

的SqlConnection分贝= DataConn.SqlConnection();

db.Open(); 
SqlTransaction transaction = db.BeginTransaction(); 

try 
{ 
    int id = 0; 

    SqlCommand sqlComm = 
      new SqlCommand(
       "procCreateChallengeMember @gameId, @creatorId, @mediatorId, @id", db, transaction) { CommandType = CommandType.Text }; 

    sqlComm.Parameters.Add(new SqlParameter("@gameId", SqlDbType.Int)).Value = 1; 
    sqlComm.Parameters.Add(new SqlParameter("@creatorId", SqlDbType.Int)).Value = 1; 
    sqlComm.Parameters.Add(new SqlParameter("@mediatorId", SqlDbType.Int)).Value = 1; 
    SqlParameter param = new SqlParameter("@id", SqlDbType.Int) 
     { 
      Direction = ParameterDirection.Output 
     }; 

    sqlComm.Parameters.Add(param); 
    sqlComm.ExecuteNonQuery(); 

    //if(param.Value != DBNull.Value) 
    //{ 
     id = Convert.ToInt32(param.Value); 
     Response.Write("One: " + id + "<br/>"); 
    //} 
    transaction.Commit(); 
    //Response.Write("Two: " + sqlComm.Parameters["expr"].Value + "<br/>"); 

} 
catch (Exception ess) 
{ 
    transaction.Rollback(); 
    Response.Write(ess.Message); 
} 

现在得到的错误 对象不能从DBNull转换为其他类型。(当我删除该IF语句时)

+0

您还没有添加“@Id”参数 - 请检查我的答案 – codingbiz

+0

已更新,已编辑 – TheGeekZn

+1

您是否真的有一个Id列,它是一个Identity列? – codingbiz

回答

0

使用SCOPE_IDENTITY后,终于找到了我自己的解决方案(即工作)。

SQL:

-- ============================================= 
-- Author:  Darren Whitfield 
-- Create date: 7 October 2012 
-- Description: This will create a new challenge holder, and return its ID 
-- ============================================= 
ALTER PROCEDURE [dbo].[procCreateChallengeMember] 
    -- Add the parameters for the stored procedure here 
    @gameId int = NULL, 
    @memberID int = NULL, 
    @mediatorID int = NULL, 
    @id int OUTPUT 
AS 
BEGIN 
    -- SET NOCOUNT ON added to prevent extra result sets from 
    -- interfering with SELECT statements. 
    -- SET NOCOUNT ON; 

    -- Insert statements for procedure here 
    INSERT INTO tblSiteChallengeMember (gameId, creatorId, mediatorId, completed, dateAdded) VALUES (@gameId, @memberId, @mediatorID, 0, GETDATE()) 

    SET @id = @@IDENTITY 
    SELECT @id AS iden 
END 

aspx.cs:

string identity = ""; 
     SqlConnection db = DataConn.SqlConnection(); 

     db.Open(); 
     SqlTransaction transaction = db.BeginTransaction(); 

     try 
     { 

      SqlCommand sqlComm = 
        new SqlCommand(
         "procCreateChallengeMember @gameId, @creatorId, @mediatorId, @id", db, transaction) { CommandType = CommandType.Text }; 

      sqlComm.Parameters.Add(new SqlParameter("@gameId", SqlDbType.Int)).Value = 2; 
      sqlComm.Parameters.Add(new SqlParameter("@creatorId", SqlDbType.Int)).Value = 1; 
      sqlComm.Parameters.Add(new SqlParameter("@mediatorId", SqlDbType.Int)).Value = 1; 
      sqlComm.Parameters.Add(new SqlParameter("@id", SqlDbType.Int) { Direction = ParameterDirection.Output }); 

      using (SqlDataReader rdr = sqlComm.ExecuteReader()) 
      { 
       while (rdr.Read()) 
       { 
        identity = rdr["iden"].ToString(); 
       } 
      } 

      Response.Write("One: " + identity + "<br/>"); 

      transaction.Commit(); 

     } 
     catch (Exception ess) 
     { 
      transaction.Rollback(); 
      Response.Write(ess.Message); 
     } 

返回ID
感谢所有那些谁把自己的时间,把他们的想法和意见。没有它,我会永远做不成。

2

“我怎样才能得到插入到我的ASP.net页面的最后一行的ID?

SELECT @id = SCOPE_IDENTITY() 

获取插入行的存储过程返回它。

编辑

在回应跟进问题。

你需要让你的SqlCommand知道一个参数已经出来了。

// Just below where you added your other params 
    SqlParameter outputParam = new SqlParameter("@id", SqlDbType.Int) 
    { 
     Direction = ParameterDirection.Output 
    }; 

    sqlComm.Parameters.Add(outputParam); 

    sqlComm.ExecuteNonQuery(); 
+3

严格来说,它将是'SELECT @id = SCOPE_IDENTITY()',因为OP表示他/她想要返回'@ id'的输出参数。 –

+0

谢谢,安。经过适当修改。 –

+0

使用了这个(@AnnL。) - >更新了我的Q给回复 – TheGeekZn

0
IF (@@error <> 1) 
    BEGIN 
    SELECT @id=scope_identity() 
    END 
ELSE 
    BEGIN 
    set @id=0 
    RETURN 0 
    END 
+0

如果没有插入错误,它会将@id值设置为最后插入的ID否则返回0 – Swati

0

从C#获取它在你的PROC

SqlParameter param = new SqlParameter("@Id", SqlType.Int); 
param.Direction = ParameterDirection.Output; 

command.Parameters.Add(param); 
command.ExecuteNonQuery(); 

int id = 0; 
if(param.Value != null) 
    id = Convert.ToInt32(param.Value) 
+0

它只返回一个DBNULL值。 – TheGeekZn