以表作为输入的存储过程事务执行了很多次,直到达到事务限制

时间:2019-03-26 20:29:55

标签: sql transactions

我正在从事交易活动。我有几个表格,如屏幕截图所示:

Diagram

我还声明了自定义数据类型:

create type TagList as table
(
    TagName varchar(255)
)

现在,我只是试图将此表作为变量传递给我的存储过程以测试其是否有效,但是当我执行以下事务时,它被执行了很多次,直到达到事务限制为止

ALTER PROCEDURE NewBlogPost
    @headline VARCHAR(255),
    @content VARCHAR(MAX),
    @userId INT,
    @categoryId INT,
    @tagId INT,
    @tags AS dbo.TagList READONLY
AS
BEGIN TRY
    BEGIN TRANSACTION
        DECLARE @postId INT

        SELECT @postId = (SELECT TOP 1 PostId
                          FROM Posts
                          ORDER BY PostId DESC) + 1;

        INSERT INTO Posts (PostId, Headline, Content, UserId, CategoryId, StateId, PostedDate, LastEdit)
        VALUES (@postId, @headline, @content, @userId, @categoryId, 1, GETDATE(), GETDATE())

        INSERT INTO TagPost (PostId, TagId)
        VALUES (@postId, @tagId)

        COMMIT TRANSACTION
    END TRY
    BEGIN CATCH
        SELECT
            ERROR_NUMBER() AS ErrorNumber,
            ERROR_SEVERITY() AS ErrorSeverity,
            ERROR_STATE() AS ErrorState,
            ERROR_PROCEDURE() AS ErrorProcedure,
            ERROR_LINE() AS ErrorLine,
            ERROR_MESSAGE() AS ErrorMessage

        ROLLBACK TRANSACTION
    END CATCH

DECLARE @TagTable TagList

INSERT INTO @TagTable(TagName)
VALUES ('Computers'), ('MobilePhones'), ('Pesos')

EXEC NewBlogPost @headline = 'Framework called VUE breaks new record', @content = 'New framework had broken world record in daily download', @userId = 1, @categoryId = 1, @tagId = 1, @tags = @TagTable

有什么主意我为什么要执行这么多次交易?

1 个答案:

答案 0 :(得分:0)

好的,我已经弄清楚了,它与Transaction无关,我无意中将exec语句放入事务中,因此创建了一个无限循环。