» Documentation » SQL Reference

If Else

Conditional execute of SQL statements.

Syntax

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

Boolean_expression

The predicate expression that returns TRUE or FALSE.

sql_statement

Any SQL statement.

statement_block

Group of SQL statements. It must be enclosed with BEGIN and END.

Example

-- Create Database & table if not exists. Update row or ,insert if row exists:
declare @dbid bigint;
select @dbid=id from system.syscatalogs where name = 'test'
if @@rowcount = 0 then CREATE DATABASE test
go;

use test;
go;

-- create table
select * from system.systables where name = 'test_1234' and catalog_id=@dbid;
if @@rowcount = 0 then
    create table test_1234
    (
    id int not null primary key,
    cnt int
    )
go;

-- update row
update test_1234
set cnt = cnt+1
where id = 0

-- insert row if update did not found any rows
if @@rowcount = 0 then
begin
    insert into test_1234 values(0,0);
    select 0 as LastValue
end
else
    -- return of the last modified row's [cnt] column's value
    select last_row(cnt) as LastValue