条件 IF 存在插入

Conditional IF Exists Insert

我有一个查询要先检查是否存在某些内容。如果是,请在 table 变量中插入一些内容。否则,将其他内容插入同一个 table 变量。

IF NOT EXISTS (SELECT 1 FROM @Main WHERE CustomerId = @CustomerId)
(   
    BEGIN  
        INSERT INTO @Result 
            SELECT .... 
            FROM ... 
            WHERE...
   END
)
ELSE
   INSERT INTO @Result  
       SELECT .... 
       FROM ...  
       WHERE...

出于某种原因,我在 NOT EXISTS 条件下不断收到以下错误...ELSE 部分完全没问题。

Incorrect syntax near the keyword 'BEGIN'
Incorrect syntax near ')'
Incorrect syntax near '@Result'

我哪里做错了?

试试这个

IF NOT EXISTS (SELECT 1 FROM @Main WHERE CustomerId = @CustomerId)

     BEGIN  
          INSERT INTO @Result 
          SELECT .... FROM ... WHERE...
     END

ELSE

     BEGIN
          INSERT INTO @Result 
          SELECT .... FROM ... WHERE...
     END

括号不属于 BEGIN/END:

IF NOT EXISTS (SELECT 1 FROM @Main WHERE CustomerId = @CustomerId)   
BEGIN  
    INSERT INTO @Result 
        SELECT .... FROM ... WHERE...
END
ELSE . . .

我还建议您为 INSERT 列出 @Result 的列。这可以防止将来出现问题。