2015-02-07 103 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