我有一个存储过程,用于一次更新两个表。
我的问题是第一个表有一个自动递增ID列(“commentID”),我的第二个表有关系,所以我需要从第一个INSERT新创建的ID才能生成第二个INSERT 。
我尝试了以下内容,我可以保存而不会出现错误,但它不会按预期执行,也不会按预期更新表格。 有人能告诉我这里我做错了什么吗?
我的SQL:
ALTER PROCEDURE [dbo].[MOC_UpdateComment]
@imgID int,
@commentID int = '999999',
@comment nvarchar(1000),
@lastUpdate nvarchar(50),
@modBy varchar(50)
AS
BEGIN
DECLARE @temp AS TABLE
(
commentID int
)
SET NOCOUNT ON;
BEGIN TRANSACTION;
INSERT INTO MOC_BlogComments
(
imgID,
comment
)
OUTPUT inserted.commentID INTO @temp(commentID)
SELECT @imgID,
@comment
INSERT INTO MOC_LogComments
(
commentID,
lastUpdate,
modTime,
modBy
)
SELECT commentID,
@lastUpdate,
GETDATE(),
@modBy
FROM @temp
COMMIT TRANSACTION;
END
答案 0 :(得分:1)
函数SCOPE_IDENTITY()返回上次插入操作的标识。您可以使用它来获取第二个INSERT语句中需要使用的值
您可以在声明中使用它:
INSERT INTO MORC_BlogComments (imgID, comment)
VALUES (@imgID, @comment)
INSERT INTO MORC_LogComments (commentID, lastUpdate, modTime, modBy)
VALUES (SCOPE_IDENTITY(), @lastUpdate, GETDATE(), @modBy)
答案 1 :(得分:1)
DECLARE @imgID INT,
@commentID INT = '999999',
@comment NVARCHAR(1000),
@lastUpdate NVARCHAR(50),
@modBy VARCHAR(50)
DECLARE @MORC_BlogComments AS TABLE
(
id INT IDENTITY(1, 1) NOT NULL,
imgid INT,
comment VARCHAR(100)
)
DECLARE @MORC_LogComments AS TABLE
(
commentid INT,
lastupdate DATETIME,
modtime DATETIME,
modby VARCHAR(100)
)
DECLARE @TEMP AS TABLE
(
commentid INT
)
SET nocount ON;
BEGIN TRANSACTION;
INSERT INTO @MORC_BlogComments
(imgid,
comment)
output inserted.id
INTO @TEMP(commentid)
VALUES (@imgID,
@comment)
INSERT INTO @MORC_LogComments
(commentid,
lastupdate,
modtime,
modby)
SELECT commentid,
@lastUpdate,
Getdate(),
@modBy
FROM @temp
SELECT *
FROM @MORC_LogComments