通过SQL为这个问题的基本性质道歉,但它来自SQL noob。
我在一些在线研究后创建了以下存储过程。该过程的目的是维护计数(VisitCount
),因此必须进行适当的锁定以保持完整性。据我所知MERGE
为这种情况提供了正确的锁定级别,但如果有人可以建议这是否正确,我会很感激。
感谢。
ALTER PROCEDURE dbo.Popularity_Update
@TermID int
AS
SET NOCOUNT ON
DECLARE @Now date = SYSDATETIME()
BEGIN TRY
MERGE Popularity AS t
USING (SELECT @TermID AS TermID, @Now AS VisitDate) AS s ON t.TermID = s.TermID
AND t.VisitDate = s.VisitDate
WHEN MATCHED THEN
UPDATE
SET VisitCount += 1
WHEN NOT MATCHED BY TARGET THEN
INSERT (TermID, VisitDate, VisitCount)
VALUES (s.TermID, s.VisitDate, 1);
END TRY
BEGIN CATCH
END CATCH
答案 0 :(得分:0)
这个怎么样....
ALTER PROCEDURE dbo.Popularity_Update
@TermID int
AS
BEGIN
SET NOCOUNT ON;
DECLARE @Now date = SYSDATETIME()
BEGIN TRY
UPDATE Popularity
SET VisitCount = COALESCE(VisitCount, 0) + 1
WHERE TermID = @TermID
AND VisitDate = @Now
IF (@@ROWCOUNT = 0)
BEGIN
INSERT INTO Popularity (TermID, VisitDate, VisitCount)
VALUES (@TermID, @Now, 1)
END
END TRY
BEGIN CATCH
END CATCH
END