我正在尝试使用以下存储过程但是有一些实例只有增量发生且代码不运行。我需要的是,当程序进入IF语句时,它应该运行两个语句或无。
存储过程如下:
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[spflpunch]
AS
BEGIN
DECLARE @id NUMERIC(18,0)
DECLARE @studname NVARCHAR(50)
DECLARE @punchtime DATETIME
DECLARE @samedaycount NUMERIC(2)
SELECT @id = (MAX(lastid)) FROM [smartswype].[dbo].[read]
PRINT @id
SELECT @studname = studname
FROM [SSWYPE_WEBDB].[dbo].[attdview]
WHERE id =@id
PRINT @studname
SELECT @punchtime = punchtime
FROM [SSWYPE_WEBDB].[dbo].[attdview]
WHERE id = @id
PRINT @punchtime
--SELECT @punchvarchar = CONVERT(VARCHAR(10),@punchtime, 103) + ' ' + CONVERT(VARCHAR(5), @punchtime, 14)
IF @id = (SELECT MAX(id) FROM [SSWYPE_WEBDB].[dbo].[attdview])
BEGIN
SELECT @samedaycount = COUNT(*)
FROM [SSWYPE_WEBDB].[dbo].[attdview]
WHERE (studname = @studname
AND CONVERT(DATE, punchtime) = CONVERT(DATE, @punchtime)) -- If firstpunch = 1 then it is the first punch
PRINT @samedaycount
IF @samedaycount =1
BEGIN
INSERT INTO [smartswype].[dbo].[firstlastpunch] ([studname], [DATE], [punch1], [punch2])
VALUES(@studname, CONVERT(DATE, @punchtime), @punchtime, NULL);
UPDATE [smartswype].[dbo].[read]
SET lastid = @id + 1;
END
ELSE IF (@samedaycount > 1)
BEGIN
UPDATE [smartswype].[dbo].[firstlastpunch]
SET punch2 = @punchtime
WHERE (studname = @studname AND DATE = CONVERT(DATE, @punchtime));
UPDATE [smartswype].[dbo].[read]
SET lastid = @id + 1;
END
END
END
答案 0 :(得分:0)
如果要确保运行两个语句或不运行任何语句,则应在事务中包装if语句的内容。
通过将其包装在事务中,您可以确保如果一个语句失败,则另一个语句将不会运行。
以下是SQL Server中交易文档的链接
https://docs.microsoft.com/en-us/sql/t-sql/language-elements/commit-transaction-transact-sql