1

如果某些列没有空值,我想编写 sql 脚本来更新我的表,如果它有空值,则不会执行更新语句,我的代码在这里引发错误并执行 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
4

2 回答 2

0

ELSE将控制下一条语句的执行,除非后面的语句被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

但是您不能在/块中使用批处理分隔符 ( GOs) - 因此您需要重新测试每个批处理中的条件或找到其他方法来阻止执行以下语句。BEGINEND

于 2013-09-18T09:24:51.587 回答
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;
于 2013-09-18T09:07:51.797 回答