插入最后创建的Id并将其用作另一个插入的参数

时间:2018-01-16 02:17:56

标签: sql stored-procedures

我有两个插入存储过程

user_id

更新

Store.Slider表:

user

Store.SliderDetail表

CREATE PROCEDURE usp_Create_Slider 
    -- Add the parameters for the stored procedure here
    @SliderId int, 
    @LanguageId int,
    @Photo varbinary(max),
    @Title varchar(250),
    @Description varchar(250),
    @IsDeleted bit = false
AS
BEGIN
    -- SET NOCOUNT ON added to prevent extra result sets from
    -- interfering with SELECT statements.
    SET NOCOUNT ON;
        BEGIN TRANSACTION

BEGIN TRY
INSERT INTO Store.Slider VALUES (@Photo)
INSERT INTO Store.SliderDetail VALUES (@SliderId,@LanguageId, @Title, @Description, @IsDeleted);
    return 1;
    COMMIT TRANSACTION
END TRY
BEGIN CATCH

EXEC usp_Sql_Error_Codes 'usp_Create_Slider'
    return 0
    ROLLBACK TRANSACTION
END CATCH

END

我想要做的是从+----------+----------------+ | SliderId | int | +----------+----------------+ | Photo | varbinary(max) | +----------+----------------+ 获取+----------------+--------------+ | SliderDetailId | int | +----------------+--------------+ | SliderId | int | | LanguageId | int | | Title | Varchar(255) | | Description | Varchar(255) | | IsDeleted | bit | +----------------+--------------+ 并在SliderDetail的第二个插入中使用as参数。 我怎样才能做到这一点?此致

1 个答案:

答案 0 :(得分:0)

从自动增量列

获取最后插入的id的查询
LAST_INSERT_ID();

这应该在INSERT INTO Store.Slider VALUES (@Photo)之后,然后您可以将它返回的值分配给SliderId,或者更好地直接在第二个插入查询中使用它

INSERT INTO Store.SliderDetail VALUES (LAST_INSERT_ID(),@LanguageId, @Title, @Description, @IsDeleted);