SQL Server在INSERT和SELECT OUTCOME上创建触发器

时间:2016-04-11 15:32:53

标签: sql-server database tsql

我尝试创建一个Trigger,它将在表中插入一个唯一ID,然后获取创建的ID并在“触发触发器”的表上使用它

所以我在我的表中插入一些数据,然后我希望触发器在另一个表(主ID表)中插入一些数据,然后需要获取刚创建的ID(自动增量INT)并将此ID添加到触发器触发的表ID。 我尝试了一些不同的选项,但它只是没有插入ID,它会给我一个错误。

希望你能帮助我。

CREATE TRIGGER  [dbo].[TROidMemoDiaryHeader]
ON  [dbo].[InvoiceDiaryHeader]
FOR INSERT
AS 
DECLARE @TEMP uniqueidentifier, @Lock INT, @Object INT,   @User V     ARCHAR(MAX), @Delay NCHAR(12), @ID INT
SET @TEMP = NEWID()
SET @Lock = '0' --staat geen wijziging meer toe
SET @Object = '5' -- aanduiding bron
SET @User = CURRENT_USER
--SET @Delay = '00:00:00:125' -- Wacht voor een kwart seconde voor     verder te gaan
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
--SET NOCOUNT ON;
    INSERT INTO [dbo].[AbstractMBOBase] ([Uid], [OptimisticLockField],     [ObjectType], [User])
    SELECT @TEMP, @Lock, @Object, @User

IF EXISTS (SELECT [Uid] FROM [dbo].AbstractMBOBase WHERE [Uid] = @TEMP)
BEGIN
    INSERT INTO [InvoiceDiaryHeader](Oid)
    SELECT Oid FROM inserted
    /*
    SELECT * INTO #tmpOID FROM AbstractMBOBase WHERE [Uid] = @TEMP
    UPDATE [dbo].InvoiceDiaryHeader SET Oid = (SELECT a.[Oid] FROM [dbo].[AbstractMBOBase] AS a  
    WHERE [Uid] = @TEMP)
    --CREATE TABLE [dbo].#TempOID()
    --SELECT * INTO #TempOID FROM INSERTED
    */

    /*
    --UPDATE [MemoDiaryHeader]
    SET @ID = (SELECT a.[Oid] FROM [dbo].[AbstractMBOBase] AS a  
    WHERE [Uid] = @TEMP)
    INSERT INTO [MemoDiaryHeader]([Oid])
    SELECT @ID 
    --FROM inserted
    --select [Oid]=i.[Oid] from inserted i
    */
    END
--END
END
GO

0 个答案:

没有答案