使用批量插入使用光标触发触发器

时间:2017-03-10 13:50:17

标签: c# sql triggers cursor bulkinsert

我正在使用BulkInsert - 工作正常 - 并且触发器 - 工作正常 - 光标不起作用我认为。请你看看我的代码并告诉我我的错误是什么?

非常感谢。

    ALTER TRIGGER [dbo].[CheckProducts] 
    ON  [dbo].[ProductsTemp]
    AFTER INSERT
    AS 
    BEGIN
        DECLARE @Name NVARCHAR(MAX);
        DECLARE @Manufacturer NVARCHAR(MAX);
        DECLARE @Source NVARCHAR(50);
        DECLARE @SOurceDetailUrl NVARCHAR(MAX);
        DECLARE @MainPrice DECIMAL;
        DECLARE @SalesPrice DECIMAL;
        DECLARE @Description NVARCHAR(MAX);
        DECLARE @ImageUrl NVARCHAR(MAX);
        DECLARE @GroupId INT;
        DECLARE @ParentCategoryId INT;
        DECLARE @CategoryId INT;

        DECLARE curs CURSOR FOR
        SELECT Name, Manufacturer, Source, SourceDetailUrl, MainPrice, SalesPrice, [Description], ImageUrl, GroupId, ParentCategoryId, CategoryId
        FROM INSERTED

        OPEN curs
        FETCH NEXT FROM curs INTO @Name, @Manufacturer, @SourceDetailUrl, @MainPrice, @SalesPrice, @Description, @ImageUrl, @GroupId, @ParentCategoryId, @CategoryId
        WHILE @@FETCH_STATUS = 0
        BEGIN 
            IF EXISTS (SELECT * FROM Products WHERE Name = @Name AND Manufacturer = @Manufacturer AND Source = @Source AND SourceDetailUrl = @SourceDetailUrl)
            BEGIN
                UPDATE Products SET MainPrice = @MainPrice, SalesPrice = @SalesPrice WHERE Name = @Name AND Manufacturer = @Manufacturer AND Source = @Source AND SourceDetailUrl = @SourceDetailUrl
            END
            ELSE
            BEGIN
                INSERT INTO Products (Name, Manufacturer, MainPrice, SalesPrice, [Description], Source, SourceDetailUrl, ImageUrl, GroupId, ParentCategoryId, CategoryId)
                VALUES (@Name, @Manufacturer, @MainPrice, @SalesPrice, @Description, @Source, @SourceDetailUrl, @ImageUrl, @GroupId, @ParentCategoryId, @CategoryId)
            END

            DELETE FROM ProductsTemp WHERE Name = @Name AND Manufacturer = @Manufacturer AND Source = @Source AND SourceDetailUrl = @SourceDetailUrl
            FETCH NEXT FROM curs INTO @Name, @Manufacturer, @SourceDetailUrl, @MainPrice, @SalesPrice, @Description, @ImageUrl, @GroupId, @ParentCategoryId, @CategoryId
        END
        CLOSE curs
        DEALLOCATE curs
    END

0 个答案:

没有答案