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

将数据添加到数据库后,如何获得唯一 ID?是否有捷径可寻?

4

3 回答 3

3

如果您的ID列是 type 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
于 2013-10-14T19:06:33.157 回答
3

其他答案向您展示了如何获取 ID(如果它是 IDENTIY)。我阅读了“唯一 ID”并假设您的 ID 是唯一标识符。所以首先,我创建了一个如下所示的表:

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

我希望这有帮助!

于 2013-10-14T19:09:39.013 回答
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

顺便说一句,始终在对象名称上使用模式前缀。另外,请不要在过程名称上使用 sp_ 前缀

于 2013-10-14T19:08:10.317 回答