2015-02-07 105 views
0

我一直在试图执行这个if和else语句。但是,每个执行都会指示错误,例如功能错误或与语法相关的错误。SQL如果和其他语句

CREATE trigger [dbo].[TRIAL] 
on [dbo].[TBL1] 

after INSERT 
AS 
BEGIN 
    SET NOCOUNT ON; 

    IF TBL1.NUMBER = TBL2.NUMBER THEN  
     insert into TBL3 (NAME,HEIGHT)  
     select NAME,HEIGHT  
     from TBL1,TBL2 

    ELSE  
     PRINT 'WRONG NUMBER' 

end 

请问您能帮我解决这个问题吗?

+2

没有'THEN'使用'BEGIN \ END'指示块; https://msdn.microsoft.com/zh-cn/library/ms182717.aspx - 该触发器无效,因为它代表 – 2015-02-07 20:35:14

+0

除IF/ELSE构造外,每个语句触发一次触发器,因此您需要编写它才能使用虚拟“插入”表来标识由语句插入的行,并根据需要加入其他表。 – 2015-02-07 22:57:47

回答

4

为了扩大对亚历克斯K公司的评论了一下:

declare @Flag bit = 1; 

-- ERROR: There is no THEN keyword. 
if @Flag = 1 then 
    select 'A'; 

-- CORRECT: Omit THEN and this works as expected. 
if @Flag = 1 
    select 'A'; 


-- ERROR: Only the first SELECT is associated with the IF, so the ELSE is unmatched. 
if @Flag = 2 
    select 'B1'; 
    select 'B2'; 
else 
    select 'C'; 

-- CORRECT: If each branch of the IF has only one statement, then this construction is okay. 
if @Flag = 2 
    select 'B1'; 
else 
    select 'C'; 

-- CORRECT: If you want multiple statements in either branch of the IF, make them into a block using BEGIN/END. 
if @Flag = 2 
begin 
    select 'B1'; 
    select 'B2'; 
end 
else 
    select 'C'; 

-- CORRECT: You can also use BEGIN/END with single statements if you like. 
if @Flag = 2 
begin 
    select 'B1'; 
    select 'B2'; 
end 
else 
begin 
    select 'C'; 
end