返回INSERT添加的新ID

时间:2013-10-14 19:04:20

标签: c# sql-server stored-procedures

ALTER PROCEDURE [dbo].[SP_ADD_CUSTOMER]
(
    @CUSTOMER_NAME VARCHAR(100)
)
AS
BEGIN
    INSERT INTO CUSTOMER
    (    
       CUSTOMER_NAME
    )
    VALUES
    (
       @CUSTOMER_NAME 
    )
END

将数据添加到数据库后,如何获取唯一ID?有一个简单的方法吗?

3 个答案:

答案 0 :(得分:3)

如果您的ID列的类型为INT IDENTITY,那么您只需使用SCOPE_IDENTITY()功能:

ALTER PROCEDURE [dbo].[SP_ADD_CUSTOMER]
   (@CUSTOMER_NAME VARCHAR(100))
AS
BEGIN
    INSERT INTO CUSTOMER(CUSTOMER_NAME)
    VALUES(@CUSTOMER_NAME)

    SELECT SCOPE_IDENTITY()  -- this will retrieve and send back the newly inserted IDENTITY value
END

答案 1 :(得分:3)

其他答案已经向您展示了如何获取ID,如果它是IDENTIY。我读了“唯一身份证”并假设您的身份证是一个独特的身份证明者。首先,我创建了一个看起来像这样的表:

CREATE TABLE [dbo].[CUSTOMER](
    [CUSTOMER_ID] [uniqueidentifier] NOT NULL,
    [CUSTOMER_NAME] [nvarchar](50) NOT NULL,
 CONSTRAINT [PK_CUSTOMER] PRIMARY KEY CLUSTERED 
(
    [CUSTOMER_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]

然后我创建了一个看起来像的存储过程:

CREATE PROCEDURE [dbo].[SP_ADD_CUSTOMER]
(
    @CUSTOMER_NAME VARCHAR(100)
)
AS
BEGIN
    DECLARE @CUSTOMER_ID UNIQUEIDENTIFIER = NEWID()

    INSERT INTO CUSTOMER
    (
        CUSTOMER_ID,
        CUSTOMER_NAME
    )
    VALUES
    (
        @CUSTOMER_ID,
        @CUSTOMER_NAME 
    )

    SELECT @CUSTOMER_ID AS CUSTOMER_ID
END

最后我执行了存储过程并返回了新的CUSTOMER_ID:

DECLARE @RC int
DECLARE @CUSTOMER_NAME varchar(100) = N'Joe'

EXECUTE @RC = [dbo].[SP_ADD_CUSTOMER] 
   @CUSTOMER_NAME
GO

我希望这有帮助!

答案 2 :(得分:2)

这是假设您的“唯一ID”是IDENTITY列。如果情况并非如此,请澄清您的问题。

ALTER PROCEDURE [dbo].[SP_ADD_CUSTOMER]
  @CUSTOMER_NAME VARCHAR(100),
  @NewID INT OUTPUT
AS
BEGIN
    INSERT dbo.CUSTOMER(CUSTOMER_NAME) SELECT @CUSTOMER_NAME;
    SET @NewID = SCOPE_IDENTITY();
END
GO

另外,always use the schema prefix on object names。另外,please don't use the sp_ prefix on procedure names