If an int variable does not receive anything from the select it is zero or not

1

Let's say I have this block:

declare @teste int
declare teste_cur cursor
for
select campo1 from tabela
.....
while @@fetch_status = 0
begin
  set @teste = 0
  select @teste = campo1 from tabela where campo2 = condicao2
end
.....

If the select does not return anything, does the @test variable continue with zero (0) or not?

Seeing the answers of the colleagues below, I decided to do this IF

if @rx_num_novo is null or @rx_num_novo = ''
    begin
        --Aquifaço meu Update/Insert/Delete
    end
    
asked by anonymous 25.04.2017 / 13:18

2 answers

2

I made a test here, and if the SELECT statement that fills a variable does not return any row, the variable does not have its value changed.

i.e.:

In your case, the fetch loop will only execute if there is at least one record in the outermost select. This way:

  • If there are records returned by the outermost select, but the internal select condition is not met in the last record fetched ( campo2 = condicao2 ), the @test variable will have zero value; li>

  • If there are records returned by the outermost select and the condition of the internal select is met in the last record obtained in fetch ( campo2 = condicao2 ), the @teste variable will have the value of the field campo1 ; >

  • If the outermost select does not return records, the variable will have the default value of the integer in SQL Server, which is null.

25.04.2017 / 13:24
1
declare @teste int
set @teste = 0;
select @teste = campo1 from tabela where campo2 = condicao2 -- considerando que volte nulo
if ( @teste is null ) 
  print 'nula'
else
  print 'não nula'

    
25.04.2017 / 13:34