如何在非自动递增的表中找到最后添加的ID?

时间:2017-09-02 13:31:45

标签: sql-server identity

如何获取最后添加的元素的ID?从我在网上搜索,我发现你可以使用@@ IDENTITY和IDENTITY_SCOPE(),但只能在添加/存在时使用。我尝试了以下但是它没有工作

CREATE TABLE Products
 (PT_ID int PRIMARY KEY, Name nvarchar(20))

 CREATE TABLE Storage(ST_ID int Primary key,Info nvarchar(20))

 CREATE TABLE ProductStorageMM
 (ST_ID int CONSTRAINT S_FK FOREIGN KEY REFERENCES Storage(ST_ID ),
 PT_ID int CONSTRAINT P_FK FOREIGN KEY REFERENCES Products(PT_ID ),
 Status int not null,
 PRIMARY KEY (ST_ID ,PT_ID )
 )

上面的表格仅用于实验。我正在尝试将值添加到Product表中时自动将存储中给定产品的所有值设置为零。

     CREATE PROCEDURE AddingProduct 
     (@PID int ,@NAME nvarchar(20))
     AS BEGIN
     INSERT INTO Products(PT_ID,Name)
     VALUES(@PID,@NAME)

     INSERT INTO PSKT (PT_ID,ST_ID,Status)
     SELECT PTT.PT_ID ,STT.ST_ID,0
     FROM (SELECT * FROM Storage) AS STT, 
          (SELECT * FROM Products WHERE PT_ID=SCOPE_IDENTITY()) AS PTT;

 END

程序不起作用。我做错了什么?

1 个答案:

答案 0 :(得分:2)

我错过了什么吗?是不是@PID使用的最后一个身份? @@ IDENTITY和SCOPE_IDENTITY用于自动增加标识。你没有在这里显示自动增量,你将身份传递给过程。这会在PSKT中为@PID插入一行,传入STORAGE中的每一行。

- >给定通过参数传递身份的代码

CREATE PROCEDURE AddingProduct 
     (@PID int ,@NAME nvarchar(20))
     AS BEGIN
     INSERT INTO Products(PT_ID,Name)
     VALUES(@PID, @NAME)

     INSERT INTO PSKT (PT_ID,ST_ID,Status)
     SELECT @PID ,STT.ST_ID,0
     FROM Storage STT

 END

- >使用自动增量和@@ identity

的示例
CREATE PROCEDURE AddingProduct 
     (@NAME nvarchar(20))
     AS BEGIN
     INSERT INTO Products(Name) --< identity is inserted through auto-increment
     VALUES(@NAME)

     set @pid = @@identity  --< we need to get the identity created in the previous step for the next step.

     INSERT INTO PSKT (PT_ID,ST_ID,Status)
     SELECT @PID ,STT.ST_ID,0
     FROM Storage STT

END