SQL-Server does not have a
real boolean data type. The closest it can offer is the
bit
data type. However, even an expression that evaluates to a
bit
data type needs to be explicetly compared to either
1
or
0
in an
if
statement as outlined
here.
With begin … end blocks
If the if
or else
part controls more than one statement then they need to be enclosed in a begin
… end
block:
if db_name() = 'PROD'
begin
print('Updating Production DB');
update tq84_bla set x = x * 2;
end
else
begin
print('Updating Test DB');
update tq84_bla set x = x - 10;
end
if [not] exists(…)
A particularly nice, imho, feature in
T-SQL is the possibility to combine the SQL operator
exists
with an
if
statement:
create table some_data (
id integer,
txt varchar(10)
);
insert into some_data values
(3, 'three'),
(5, 'five' ),
(9, 'nine' );
if not exists (select * from some_data where id between 6 and 8) begin
print('No record found, insert one');
insert into some_data values (7, 'seven');
end;
select * from some_data;