Write alternative query in MSSQL view - sql-server

I need to write a view which selects records from table1 if table1 does not contain so it goes to next alternative table like table2 or table3 etc.
Pl advice.

If what you need is to find the first match and return the results...then a view is not going to help you here. You need a stored procedure instead...something like...
create procedure spname
as
begin
if exists (select * from table1 [where clause condition])
select * from table1
else if exists (select * from table2 [where clause condition])
select * from table2
else if exists (select * from table3 [where clause condition])
select * from table3
end

Related

Multiple OR operator in Snowflake in WHERE Clause is not working

I am trying to do below
Table 1
Table 2
I am writing a query like below to ensure that if any of the NOT IN satisfies, those records should be filtered out.
SELECT * FROM TABLE1
WHERE TABLE1."DEPTID" NOT IN (SELECT TABLE2."DEPTID" FROM TABLE2)
OR
TABLE1."EMPCOUNTRY" NOT IN (SELECT TABLE2."EMPCOUNTRY" FROM TABLE2)
OR
TABLE1."EMPZONE" NOT IN (SELECT TABLE2."EMPZONE" FROM TABLE2)
But it errors out
What am I doing wrong?
Edited : Exact Query is working with nvl , but result set is not as per requirement.
SELECT * FROM TABLE1 AS T1
WHERE
(
UPPER (T1."DEPTID") NOT IN
(SELECT UPPER (nvl (T2."DEPTID", '')) FROM TABLE2 AS T2)
OR
UPPER (T1."EMPZONE") NOT IN
(SELECT UPPER (nvl (T2."EMPZONE",'')) FROM TABLE2 AS T2)
)
Result - set is not as per requirement, it should filter out if there any DEPTID in the Table2 or if there is any EMPZONE in table 2 or both etc.
What should be the best way to achieve this?
I think the issue is about NULL values coming from the subqueries. Could you try to use something like this?
SELECT * FROM TABLE1 AS T1
WHERE
(
NOT EXISTS (SELECT 1 FROM TABLE2 T2 WHERE equal_null( UPPER(T1."DEPTID"), UPPER(T2."DEPTID")) )
OR
NOT EXISTS (SELECT 1 FROM TABLE2 T2 WHERE equal_null( UPPER(T1."EMPZONE"), UPPER(T2."EMPZONE")) )
);
Also here is a sample to demonstrate why you can't use NOT IN with a subquery returning NULL values:
create table NULL_TABLE ( v varchar);
insert into NULL_TABLE values (NULL),('ABC');
create or replace table MAIN_TABLE ( v varchar);
INSERT INTO MAIN_TABLE values
('Jack'),('Joe'),('ABC');
select * from MAIN_TABLE
where v NOT IN (select v FROM NULL_TABLE);
The last query returns NULL, because we can't determine if a value does not exist in series of numbers where some of them are not known - the last WHERE clause.
When using NOT IN the subquery should not allow null values as reselut, second conditions to happen all at once should be joined with AND instead of OR.
NOT (cond1 OR cond2 OR cond3)
<=>
(NOT cond1) AND (NOT cond2) AND (NOT cond3)
De Morgan's law: "The negation of a disjunction is the conjunction of the negations"
The final query should rather be:
SELECT *
FROM TABLE1 AS T1
WHERE T1."DEPTID" NOT IN (SELECT T2."DEPTID" FROM TABLE2 T2
WHERE T2."DEPTID" IS NOT NULL)
AND T1."EMPCOUNTRY" NOT IN (SELECT T2."EMPCOUNTRY" FROM TABLE2 T2
WHERE T2."EMPCOUNTRY" IS NOT NULL)
AND T1."EMPZONE" NOT IN (SELECT T2."EMPZONE" FROM TABLE2 T2
WHERE T2."EMPZONE" IS NOT NULL);

TSQL Conditional Select Statement

Is it possible to write a SQL query that does the following:
Select * From Table1
if there are results, return them. Otherwise, use an alternative query and return it's results:
Select * From Table2
I came ups with the following, but it does not seem to work:
IF EXISTS(select * From TableA)
begin
Select * from TableA
end
else
Select * from TableB
Is there a simple elegant way of accomplishing this?
You can do a UNION query with NOT EXISTS:
SELECT * FROM TABLE1
UNION ALL
SELECT * FROM TABLE2 WHERE NOT EXISTS (SELECT * FROM TABLE1)
*Assuming the columns and types are the same
If both tables have same number of columns and the column names are same then you use Union, like below.
Select * from TableA
Union
Select * from TableB
If they have different column names or different number of columns then you can use below code.
Select Col_1 as col1, col_2 as col2.... From TableA
Union
Select col_a as Col1, col_b as Col2..... From TableB

SQL Server subquery for count in 2nd table

I would like to add the count result of a 2nd query to the result set which queries the 1st table and connect this subquery with the ID of the 1st Table result. This simplified code explains it:
Select
ID_Field_Table1,
(Select Count(x)
From Table2
Where ID_Field_Table2 = ID_Field_Table1) As mycount
From Table1
What is the correct syntax?
Thanks
This code is simplified but the construction is the same. In my DB the ID_Field_Table2 and ID_Field_Table1 have the same name (let's say ID_Field). If I use this same Name, the SubQuery goes like "...Where ID_Field = ID_Field.." and this always Returns a Reslut, because it is not connecting the queries ("Select a Where x = x" returns any record in the table 2).
Select
ID_Field AS ID1,
(Select Count(x)
From Table2
Where ID_Field = ID1) As mycount
From Table1
It just returns an error, saying that ID1 does not exist.
When I use the original name of the columns (which are the same), the result is wrong
When I us an alias, an error occurs
So I think the query is wrong at all.
Well, you can't use an alias defined in the select clause, but you can use the aliases defined in the from clause:
Select
ID_Field AS ID1,
(Select Count(x)
From Table2
Where ID_Field = t1.ID_Field) As mycount
From Table1 t1
You can also do it without an alias, since the sub query is for a different table:
Select
ID_Field AS ID1,
(Select Count(x)
From Table2
Where ID_Field = Table1.ID_Field) As mycount
From Table1
However, I suspect a query using left join to a derived table as suggested in esta's answer would have better performance.
Something like this?
Select
Table1.ID_Field_Table1,
T2.MYCOUNT
From Table1
LEFT JOIN (SELECT ID_Field_Table2, COUNT(x) AS MYCOUNT FROM TABLE2 GROUP BY ID_FIELD_TABLE2) T2 ON T2.ID_Field_Table2=Table1.ID_Field_Table1
Try This query once it may help you.
Select ID_Field_Table1,COUNT_NBR
cross apply
(
Select Count(x) as COUNT_NBR
From Table2
Where ID_Field_Table2 = ID_Field_Table1
group by ID_Field_Table1
) As mycount
From Table1

SQL Server : how to check if a row exist in other tables

I would like to ask for help if how can I write a T-SQL query that checks if a row exists in other tables and insert the data in a temporary table.
For example, I have 5 tables main1, table2, table3, table4 and table5. Each table has a product_id column.
I need main1.product_id (values A000 to A010) to check if they exist in table2, table3, table4 and table5.
If it is found in table2, the value "A000" will be inserted into a temporary table. If it is not found, it will check in table3; again if not found, it will check in table4.
Then main1.product_id value "A001" will be checked. If A001 is found in table2 it won't be checked in table3 and table4 anymore, it will be written into the temp table and next value is to be checked from main1 table, and so on,...
Thanks so much
Looks like you're looking for something like this:
insert into #tmp
select product_id
from main1 m
where
(
exists (select 1 from table2 t where t.product_id = m.product_id)
or exists (select 1 from table3 t where t.product_id = m.product_id)
or exists (select 1 from table4 t where t.product_id = m.product_id)
or exists (select 1 from table5 t where t.product_id = m.product_id)
)
This will check each of the tables, and if the row is found, inserts it into #tmp
Or, alternatively, you could just use UNION ALL like in
Insert into #tmp
Select product_id from main1 where exists
(select 1 from (
select product_id p from table2 union all
select product_id from table3 union all
select product_id from table4 union all
select product_id from table5
) all where p=product_id )

Select matching records from Table 1 if Table 2 has records, otherwise select all from Table 1

Situation:
I have two tables
Table 1 always has records
Table 2 is the result of a select statement and may or may not have records
Desired Results:
If Table 2 has ANY records, I want only matching records from Table 1. Otherwise, I want all records from Table 1.
I realize I can do this:
DECLARE #count int
SELECT #count=COUNT(*) FROM Table2
IF #count>0
SELECT t1.* FROM Table1 t1 INNER JOIN Table2 t2 ON t1.id=t2.id
ELSE
SELECT * FROM Table1
However, I am trying to avoid IF statements if possible.
Is that even possible?
select t1.*
from Table1 t1
left join
Table2 t2
on t1.id = t2.id
where t2.id is not null -- Match found
or not exists -- Or Table2 is empty
(
select *
from Table2
)

Resources