How can I do to create a script in SQL where a SELECT runs, and according to the result of a column of this first, a certain condition of another table?
example:
select * from tabela as t
SE t.saldo = 0 entao WHERE t2.outracondicao = 'condicao'
How can I do to create a script in SQL where a SELECT runs, and according to the result of a column of this first, a certain condition of another table?
example:
select * from tabela as t
SE t.saldo = 0 entao WHERE t2.outracondicao = 'condicao'
SELECT *
FROM tabela AS t
WHERE (t.saldo = 0
AND EXISTS (SELECT 1
FROM tabela2 AS t2
WHERE t2.outracondicao = 'condicao'))
-- OR t.saldo <> 0
When the balance is equal to zero, the search will only be performed if the condition of the second table is met (as you did not show the structure of the tables, I kept the "information" in the question).
The commented passage ( --OR t.saldo <> 0
) can be used if you need to. It will execute the query if the balance is nonzero.
Another alternative is that the before query should be validated. If the validation in tabela2
is independent of tabela
, it can be done like this:
IF EXISTS (SELECT 1 FROM tabela2 AS t2 WHERE t2.outracondicao = 'condicao')
BEGIN
SELECT *
FROM tabela AS t
WHERE t.saldo = 0
END
As suggested by @rbz , I've created a example online for validation.
In this case, if you have two fields in common within the two tables, you can use WHERE IN
Let's say there is the ID field in table2 that is also present in table1. You could do this:
SELECT * FROM tabela2 WHERE id IN (SELECT id FROM tabela1 WHERE saldo='0')
This query will fetch all records from table2 that are also present in table1, but only with balance 0.
This mode may help you:
SELECT t.* FROM tabela t
JOIN tabela2 t2
ON t2.id = t.id
WHERE
t2.outracondicao = (CASE
WHEN t.saldo = 0
THEN 'condicao'
END)