Date choices

-1

Good afternoon guys,

I want to make a iif in sql that if the FLAG field equals "" it will bring the date of the DTDIGIT column and store it in the variable @dataInicio and when FLAG is "S " it brings the date of the EMISSAO column and stores it in the @dataFIM variable.

Then I declare these variables, because this _ query_ will become a function.

Can anyone help me?

    
asked by anonymous 11.01.2018 / 19:59

1 answer

0

If there is a single line with the FLAG column containing "S" and another line containing the "E" value, both of which meet the filter defined in the WHERE clause, the code below returns what is requested.

-- código #1
SELECT @dataInicio= case when FLAG = 'E' then DTDIGIT else @dataInicio end,
       @dataFim= case when FLAG = 'S' then EMISSAO else @dataFim end
  from tabela
  where ...;

Example:

-- código #2
CREATE TABLE Config (FLAG char(1), DTDIGIT date, EMISSAO date);

INSERT into Config values
  ('E', '20120303', NULL), ('S', NULL, '20120403');

declare @dataInicio date, @dataFim date;

SELECT @dataInicio= case when FLAG = 'E' then DTDIGIT else @dataInicio end,
       @dataFim= case when FLAG = 'S' then EMISSAO else @dataFim end
  from Config;

SELECT @dataInicio, @dataFim; 

However, if there is more than one line with the same value for the FLAG column, the variable fill is undetermined.

    
12.01.2018 / 12:56