Merge two IF or more

Asked

Viewed 132 times

1

I need to unite some if's and I’m having difficulties,

I’ve tried using with the union, but to no avail.

The query I’m running is:


IF (select count(Estado)

  FROM tbl_1
    where Estado != 'WIP' AND Estado !='on hold') > 0

    BEGIN
    SELECT 'Estado NOK: ', Nome, (Estado), SLA from tbl_1 
    where (Estado != 'WIP' AND Estado !='on hold')

    END

ELSE
    BEGIN
    SELECT 'Estado OK'

    END 


----------


//e o outro if seria:


----------


IF (select count(SLA) 

    FROM tbl_1
        where SLA != '24x7' AND SLA != '10x8') >0

    BEGIN
    SELECT 'Dados NOK: ', Nome, Estado, (SLA) from tbl_1 
    where (SLA != '24x7' AND SLA != '10x8')

    END

ELSE
    BEGIN
    SELECT 'Dados OK' 

    END 

What I need is for these two querys to be joined into one.

  • Which DBMS? Looks like Sqlserver, I’m sure?

  • That’s right @Jefferson

1 answer

0

You can do this using a dynamic sql:

DECLARE @SQL VARCHAR(MAX)
SELECT @SQL = ''

IF (/*CONDICAO 1*/)
BEGIN
    SELECT @SQL = @SQL + 'PESQUISA TRUE '
END
ELSE
    SELECT @SQL = @SQL + 'PESQUISA FALSE '

SELECT @SQL = @SQL + 'UNION '

IF (/*CONDICAO 2*/)
BEGIN
    SELECT @SQL = @SQL + 'PESQUISA TRUE '
END
ELSE
    SELECT @SQL = @SQL + 'PESQUISA FALSE '

EXEC(@SQL)

But to use Union the two queries, when true or false, must return the same number of columns.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.