5

当我尝试通过 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

4 回答 4

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);
于 2012-09-20T09:08:56.323 回答
2

作为使用ExecuteScalar. 你的第一个执行语句是INSERT这样它返回插入的记录数。

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

string Query = @"SET NOCOUNT ON;
INSERT INTO table1(name) values('ttt');
SELECT SCOPE_IDENTITY(); SET NOCOUNT OFF;
";
于 2012-09-20T10:13:47.830 回答
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());
于 2012-09-20T09:06:53.120 回答
0

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

@RecordID int OUTPUT

...这里是插入语句

SET @RecordID= SCOPE_IDENTITY();

...

SELECT @RecordID
于 2012-09-20T09:05:18.400 回答