如果条件为真,则引发错误并且不执行else块

时间:2013-09-18 08:59:56

标签: sql-server tsql

我想编写sql脚本来更新我的表,如果某些列没有空值,如果它有空值,则不会执行update语句,我的代码在这里引发错误并执行else块,为什么?

IF EXISTS(select 1 from Trendline.Invoices where Trx_Date is null or Trx_no is null or OperaKey is null) 
     RAISERROR('This script can not been executed because of null value/values in this columns.',0,1)
ELSE

BEGIN TRANSACTION
SET QUOTED_IDENTIFIER ON
SET ARITHABORT ON
SET NUMERIC_ROUNDABORT OFF
SET CONCAT_NULL_YIELDS_NULL ON
SET ANSI_NULLS ON
SET ANSI_PADDING ON
SET ANSI_WARNINGS ON
COMMIT
BEGIN TRANSACTION
GO
ALTER TABLE Trendline.Invoices
    DROP CONSTRAINT FK_Invoices_RecSkpUser
GO
ALTER TABLE Trendline.Invoices
    DROP CONSTRAINT FK_Invoices_RecConfSkpUsr
GO
ALTER TABLE Trendline.Invoices
    DROP CONSTRAINT FK_Invoices_FollowUpSkpUsr
GO
ALTER TABLE TaeppaCore.Users SET (LOCK_ESCALATION = TABLE)
GO
COMMIT
BEGIN TRANSACTION
GO
ALTER TABLE Trendline.Invoices
    DROP CONSTRAINT FK_Invoices_Currencies

2 个答案:

答案 0 :(得分:0)

您可以根据需要使用函数或plsql块。

Declare
procedurename p(sales NUMBER)
BEGIN
IF sales>100 THEN
UPDATE STOCK set SALES=sales-100;
ELSE
DBMS_OUTPUT.PUT_LINE('SOME COMMENT');
END IF
END p;

答案 1 :(得分:0)

ELSE将控制 next 语句的执行,除非后面的BEGIN/END块包围。所以:

IF EXISTS(select 1 from Trendline.Invoices where Trx_Date is null or Trx_no is null or OperaKey is null)
     --The next line executes if the IF was taken
     RAISERROR('This script can not been executed because of null value/values in this columns.',0,1)
ELSE

--The next line executes if the ELSE was taken
BEGIN TRANSACTION
--The next line executes whether either branch was taken
SET QUOTED_IDENTIFIER ON

因此,通常的建议是围绕BEGIN / END块应该采用的所有内容,例如:

IF EXISTS(select 1 from Trendline.Invoices where Trx_Date is null or Trx_no is null or OperaKey is null) 
     RAISERROR('This script can not been executed because of null value/values in this columns.',0,1)
ELSE
BEGIN
  BEGIN TRANSACTION
  SET QUOTED_IDENTIFIER ON
  SET ARITHABORT ON
  SET NUMERIC_ROUNDABORT OFF
  SET CONCAT_NULL_YIELDS_NULL ON
  SET ANSI_NULLS ON
  SET ANSI_PADDING ON
  SET ANSI_WARNINGS ON
  COMMIT
END

但您不能在GO / BEGIN块内部使用批处理分隔符(END) - 因此您需要重新测试每个批次中的条件或查找防止以下语句执行的其他方法。