如何在SQL Server过程中正确构造if语句?

时间:2014-07-21 20:06:22

标签: sql sql-server

我想在存储过程中编写一个SQL if语句,它将是这样的:

...........
if B is not null{
  if A is null{
    insert B to database
  }
  else if A != B but A is not null{
    update B to replace A
  }
  else(when A = B){
     do nothing
  }
}
.....other codes.....

我的问题是我不知道如何写作"什么都不做"在A = B场景中,有没有办法正确构造这个if语句?或者我应该只使用两个条件吗?

2 个答案:

答案 0 :(得分:3)

您可以省略ELSE声明的IF...ELSE部分。

http://msdn.microsoft.com/en-us/library/ms182717.aspx

IF Boolean_expression 
     { sql_statement | statement_block } 
[ ELSE 
     { sql_statement | statement_block } ] 

ELSE周围的括号表示它是可选的。

我建议您阅读有关Control-of-Flow Language的其他主题。

答案 1 :(得分:0)

就个人而言,我尽量不围绕SQL包含这种逻辑。我会完全摆脱ifs。

insert into <table> (<fields>)
    SELECT B
    WHERE B is not null
    AND A is null

UPDATE <table>
SET <field>=B
WHERE A is not null
AND B is not null
AND A <> B
AND <field>=A

MERGE声明也可以。