SCOPE_IDENTITY()不起作用

时间:2012-09-20 08:52:26

标签: asp.net sql sql-server

当我尝试通过SQL Server在数据库中插入最后一个ID时,它返回__Page。这是我的代码:

query = "INSERT INTO
             seekers(name, sname, lname, status, gender, dob, major, experince,
                     email, password, phone, valid, city)
             values (@name, @sname, @lname, @status ,@gender, @dob, @major,
                     @exp, @email, @password, @phone, 0, @city);
         SELECT SCOPE_IDENTITY();";

// some code here related to parameters

command = new SqlCommand(query, connection);
int id = Convert.ToInt32(command.ExecuteScalar());

4 个答案:

答案 0 :(得分:4)

如果您只想SELECT使用OUTPUT;

INSERT INTO seekers(name,sname,lname,status,gender,dob,major,experince,email,password,phone,valid,city)
OUTPUT INSERTED.IDENTITY_COL_NAME
values(@name,@sname,@lname,@status,@gender,@dob,@major,@exp,@email,@password,@phone,0,@city);

答案 1 :(得分:2)

使用ExecuteScalar。你首先执行的语句是INSERT,所以它返回插入的记录数。

为避免这种情况,请使用SET NOCOUNT ON,如下所示:

string Query = @"SET NOCOUNT ON;
INSERT INTO table1(name) values('ttt');
SELECT SCOPE_IDENTITY(); SET NOCOUNT OFF;
";

答案 2 :(得分:1)

您可以编写类似的存储过程;

CREATE PROCEDURE [seekers_Insert]
 @ID uniqueidentifier OUTPUT,
 @name nvarchar(50) ,
  @sname nvarchar(50),

(other input parameters)
  AS
  INSERT INTO seekers(name,sname,lname,status,gender,dob,major,experince,email,
                         password,phone,valid,city)
                  values(@name,@sname,@lname,@status,@gender,@dob,@major,@exp,@email,
                         @password,@phone,0,@city)

   SET @ID=SCOPE_IDENTITY()
    GO

以后你可以把它拿走

int ID = Convert.ToInt32(Command.ExecuteScalar());

答案 3 :(得分:0)

我们这样做并且工作正常,但我们在我们的存储过程中使用返回参数:

@RecordID int OUTPUT

...这里是插入语句

SET @RecordID= SCOPE_IDENTITY();

...

SELECT @RecordID