SQL不在if语句中更新

时间:2017-11-08 12:59:40

标签: sql sql-server

我尝试使用SQL从表单插入或更新数据,但我收到错误“Incorect syntax near')'。关键字'else'附近的Incorect语法”

IF EXISTS
(
    SELECT 1
    FROM TableName
    WHERE ID = ID_from_form_field
)
    UPDATE TableName
      SET
          Name = 'Name_from_form_field',
          UniqueNumber = uniquenumber_from_form_field
    WHERE ID = ID_from_form_field;
    ELSE
INSERT INTO TableName
(Name,
 UniqueNumber
)
VALUES
('Name_from_form_field',
 uniquenumber_from_form_field
);

4 个答案:

答案 0 :(得分:1)

在此之前您可能遇到代码问题。但对于此类代码,请使用分号和begin / end块:

if exists (select 1 from TableName where ID = ID_from_form_field)
begin
    update TableName
       set Name = 'Name_from_form_field',
           UniqueNumber = uniquenumber_from_form_field
       where ID = ID_from_form_field;
end;
else
begin
   insert into TableName (Name, UniqueNumber)
       values ('Name_from_form_field', uniquenumber_from_form_field);
end;

答案 1 :(得分:0)

使用begin& end它就像C / ++ /#etc中的{}一样。

IF EXISTS
(
    SELECT 1
    FROM TableName
    WHERE ID = ID_from_form_field
)
    BEGIN
        UPDATE TableName
          SET
              Name = 'Name_from_form_field',
              UniqueNumber = uniquenumber_from_form_field
        WHERE ID = ID_from_form_field;
END;
    ELSE
    BEGIN
        INSERT INTO TableName
        (Name,
         UniqueNumber
        )
        VALUES
        ('Name_from_form_field',
         uniquenumber_from_form_field
        );
END;

答案 2 :(得分:0)

只需添加开头和结尾

    IF EXISTS(SELECT 1 
          FROM   tablename 
          WHERE  id = id_from_form_field) 
  BEGIN 
      UPDATE tablename 
      SET    NAME = 'Name_from_form_field', 
             uniquenumber = uniquenumber_from_form_field 
      WHERE  id = id_from_form_field 
  END 
ELSE 
  BEGIN 
      INSERT INTO tablename 
                  (NAME, 
                   uniquenumber) 
      VALUES      ('Name_from_form_field', 
                   uniquenumber_from_form_field) 
  END 

答案 3 :(得分:0)

请更新您的查询,如下所示。您错过了在if和else之后为SQL Server查询添加BEGIN和END

auto const programEntry = x3::skip(blankOrComment) [program >> x3::omit[*blankOrComment]];