简体   繁体   English

在SQL Server存储过程中选择插入的行

[英]Select inserted row in SQL Server stored procedure

I am inserting some values into a table using the INSERT command then I am getting it's inserted value as OUTPUT . 我正在使用INSERT命令将一些值插入到表中,然后得到它的插入值OUTPUT Now I want to select the inserted row by its id using the SELECT command I am using the following code but it doesn't seem to work. 现在,我想使用SELECT命令通过其ID选择插入的行,我正在使用以下代码,但它似乎不起作用。

CREATE PROCEDURE [dbo].[SP_UserRegistration]
(
    @Name VARCHAR(100),
    @Contact VARCHAR(20),
    @DOB VARCHAR(20),
    @MailAddress VARCHAR(500),
)
AS
BEGIN
    BEGIN TRY

    DECLARE @id INT

    INSERT INTO Customer (Name, Contact, DOB, MailAddress)
    OUTPUT inserted.ID INTO @id
    VALUES (@Name, @Contact, @DOB, @MailAddress)

    SELECT * 
    FROM Customer
    WHERE ID = @id

    END TRY
    BEGIN CATCH
        PRINT('Error in SP_UserRegistration')
    END CATCH
END

You could also use an output parameter instead of select to return the rows back to your application. 您也可以使用输出参数而不是select来将行返回给您的应用程序。

If your Id is generated by a sequence , use next value for : 如果您的Id是由sequence生成的,则将next value for

create procedure [dbo].[usp_UserRegistration] (
    @Name varchar(100),
    @Contact varchar(20),
    @dob varchar(20),
    @MailAddress varchar(500),
    @Id int output
) as
begin;
set nocount, xact_abort on;
  begin try;
    begin tran
      /* your critiera for a new record here */
      select  @Id = Id
        from  dbo.Customer with (updlock, serializable)
        where Name = @Name
          and dob = @dob;
      if @@rowcount = 0
      begin;
        set @Id = next value for dbo.IdSequence /* with your Sequence name here */
        insert into dbo.Customer (Id, Name, Contact, dob, MailAddress)
        values (@Id, @Name, @Contact, @dob, @MailAddress ); 
      end;
    commit tran;
  end try
  begin catch;
    if @@trancount > 0 
      begin;
        rollback transaction;
        throw;
      end;
  end catch;
go

If your Id is an identity column, use scope_identity() . 如果您的Id是一个identity列,请使用scope_identity()

There is a big difference between @@identity , scope_identity() , and ident_current() . @@identityscope_identity()ident_current()之间有很大的区别

References: 参考文献:

Sequences: 顺序:

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM