T-SQL. How do we get the I.D. back on the record?



  • I've written a repository that adds data to the table.

    create procedure AddAddress(@Postcode nvarchar(50),@Region nvarchar(50),@Area nvarchar(50),@City nvarchar(50),@Street nvarchar(50),@House nvarchar(50))
    as
    begin
    insert into Address(Postcode,Region,Area,City,Street,House)
    values(@Postcode,@Region,@Area,@City,@Street,@House)
    end
    

    I can't figure out how to retrieve the idAddress. For example, I tried:

    create procedure AddAddress(@Postcode nvarchar(50),@Region nvarchar(50),@Area nvarchar(50),@City nvarchar(50),@Street nvarchar(50),@House nvarchar(50),
    @IdAddress int output)
    as
    begin
    insert into Address(Postcode,Region,Area,City,Street,House)
    values(@Postcode,@Region,@Area,@City,@Street,@House)
    set @IdAddress=idAddress
    end
    

    But sql server 2012 fights and refuses to establish a procedure. And if possible, share your knowledge of how to get this conclusion on the side of the C# application. I use SqlConnection to connect. The procedure itself is initiated directly with SqlCommand. Thank you.



  • Response to the first part of the question: https://ru.stackoverflow.com/questions/417984/ ♪

    Obtaining output parameter on side C#:

    SqlParameter pvNewId = new SqlParameter();
    pvNewId.ParameterName = "@IdAddress";
    pvNewId.DbType = DbType.Int32;
    pvNewId.Direction = ParameterDirection.Output;
    command.Parameters.Add(pvNewId);
    

    command.ExecuteNonQuery();

    var newID = command.Parameters["@IdAddress"].Value;




Suggested Topics

  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2