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

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 )

Related

Find matched column records in one table that may be in multiple columns in a second table

I have two tables, Table 1 with multiple columns, name, ID number, address, etc. And Table 2 with columns, ID number 1 and ID number 2 and a few other columns.
I am trying to get a T-SQL query returning all rows in Table 1 with an indicator showing whether the ID number in Table 1 matches either ID_1 or ID_2 in Table 2. The result set would be all columns from Table 1 , plus the indicator “Matched” if the ID number in Table 1 matches either ID_1 or ID_2 in Table 2.
Table 1: ID | Name | Address |
Table 2: ID_1 | ID_2
Result
T1.ID, Name, Address, ("Matched"/"Unmatched") ...
Also, would it be the same to do the opposite, meaning instead of the result including all rows from Table 1 that have a matching ID in ID_1 or ID_2 in Table 2, the result set would include only records from Table 1 where t1.ID = (T2.ID_1 or T2.ID_2)?
SELECT DISTINCT
CASE
WHEN (table1.ID = table2.ID_1 )
THEN 'Matched'
ELSE 'Unmatched'
END AS Status ,
table1.*
FROM
table1
LEFT JOIN
table2 ON table1.ID = table2.ID_1
UNION
SELECT DISTINCT
CASE
WHEN (table1.ID = table2.ID_2)
THEN 'Matched'
ELSE 'Unmatched'
END AS Status,
table1.*
FROM
table1
LEFT JOIN
table2 ON table1.ID = table2.ID_2
I think that a correlated subquery with an exists condition would be a reasonable solution:
select
t1.*,
case when exists (select 1 from table2 t2 where t1.id in (t2.id_1, t2.id_2))
then 'Matched'
else 'Unmatched'
end matched
from table1 t1
And the other way around:
select
t2.*,
case when exists (select 1 from table1 t1 where t1.id in (t2.id_1, t2.id_2))
then 'Matched'
else 'Unmatched'
end matched
from table2 t2
If you want to "align" the rows based on the match for the whole dataset at once, then you might want to try a full join:
select t1.*, t2.*
from table1 t1
full join table2 t2 on t1.id in (t2.id_1, t2.id_2)

How to join the table

Here i have 2 tables and i need to join the table as i am a beginner please help me to solve
Table1 Table2
ins1 ins2 ins3 Insc0
1 2 0 1
3 4 0 2
5 6 0 3
4
5
is this below code right?
select t2.insco from table1 t1
join table2 t2 on t1.ins1=t2.insco
union
select t2.insco from table1 t1
join table2 t2 on t1.ins2=t2.insco
union
select t2.insco from table1 t1
join table2 t2 on t1.ins3=t2.insco
As I mentioned, you need to normalise your data. This is every much overly simplified, due to the simplicity of your data, however, should get you on the right path:
CREATE TABLE dbo.YourTable1 (RowID int--,
--Other columns, but no ins1, 2, etc columns
);
INSERT INTO dbo.YourTable1 (RowID--,
--Other columns
)
VALUES(1),(2),(3);--Obviouslu, again you would have other columns, but not an ins columns
CREATE TABLE dbo.YourTable2 (Insc0 int);
INSERT INTO dbo.YourTable2 (Insc0)
VALUES(1),(2),(3),(4),(5);
CREATE TABLE dbo.LinkTable (RowID int,
Ins int);
INSERT INTO dbo.LinkTable (RowID,
Ins)
VALUES(1,1),(1,2),
(2,3),(2,4),
(3,5),(3,6);
GO
SELECT *
FROM dbo.YourTable1 YT1
JOIN dbo.LinkTable LT ON YT1.RowID = LT.RowID
JOIN dbo.YourTable2 YT2 ON LT.Ins = YT2.Insc0;
GO
--Clean up
DROP TABLE dbo.LinkTable;
DROP TABLE dbo.YourTable2;
DROP TABLE dbo.YourTable1;

SQL Server insert new rows ONLY based on multiple columns

I searched in SO but couldn't find anything for my purpose. I need to insert unique rows ONLY from one table into another. I have:
table1
id name bookid bookname start_date end_date rel_date rel_id
1 horror 1221 rockys 04/01/2016 04/30/2016 05/01/2016 4545
2 horror 1331 elm 04/01/2016 04/30/2016 05/01/2016 5656
table2
id name bookid bookname start_date end_date rel_date rel_id
1 horror 1221 rockys 04/01/2016 04/30/2016 05/01/2016 4545
2 horror 1441 elm 04/01/2016 04/30/2016 05/01/2016 5656
I need to insert into table1 the row with id = 2 in table2 AND also delete the row with id = 2 from table1, because bookid is different even though the rest of the columns match.
I tried following:
insert into table1
select * from table2
where not exists (select * from table2 where table1.id = table2.id
and table1.name = table2.name and table1.bookid = table2.bookid and
table1.bookname = table2.bookname and table1.start_date = table2.start_date
and table1.end_date = table2.end_date and table1.rel_date = table2.rel_date
and table1.rel_id = table2.rel_id)
Any way I can do all of this in one sql block?
In theory the following merge statement should achieve what you are looking for.
MERGE table1 [Target]
USING table2 [Source]
ON ([Target].[name] = [Source].[name]
AND
[Target].[bookname] = [Source].[bookname]
AND
[Target].[start_date] = [Source].[start_date]
AND
[Target].[end_date] = [Source].[end_date]
AND
[Target].[rel_date] = [Source].[rel_date]
AND
[Target].[rel_id] = [Source].[rel_id]
)
WHEN MATCHED AND ([Target].[bookid] <> [Source].[bookid]) THEN
UPDATE
SET [Target].[name] = [Source].[name]
,[Target].[bookid] = [Source].[bookid]
,[Target].[bookname] = [Source].[bookname]
,[Target].[start_date] = [Source].[start_date]
,[Target].[end_date] = [Source].[end_date]
,[Target].[rel_date] = [Source].[rel_date]
,[Target].[rel_id] = [Source].[rel_id]
WHEN NOT MATCHED THEN
INSERT(
[name]
,[bookid]
,[bookname]
,[start_date]
,[end_date]
,[rel_date]
,[rel_id]
)
VALUES
(
[Source].[name]
,[Source].[bookid]
,[Source].[bookname]
,[Source].[start_date]
,[Source].[end_date]
,[Source].[rel_date]
,[Source].[rel_id]
);
Note that there are some risks and limitations to this approach. If your [id] column has a uniqueness constraint, then it should be set as an identity column otherwise you will run into uniqueness violation errors. Also if [id] column value in table1 is different to [id] column in table2 then merge statement will keep the original [id] value from table1.
Basically this query simply updates your existing record in table1 with the matching record in table2 and insert new records from table2 into table1 if they don’t already exists.
All you should need to achieve your objective is this:
UPDATE T1
SET T1.bookid = T2.bookid
FROM Table1 T1
JOIN Table2 T2
ON T1.ID = T2.ID
However, to answer the question exactly as it was asked:
DELETE T1
FROM Table1 T1
JOIN Table2 T2
ON T1.ID = T2.ID
AND T1.bookid <> T2.bookid
INSERT INTO Table1
SELECT id, name, bookid, bookname, start_date, end_date, rel_date, rel_id
FROM Table2 T2
LEFT OUTER JOIN Table1 T1
ON T1.ID = T2.ID
AND T1.bookid = T2.bookid
WHERE T1.id IS NULL
Note that if your ID fields aren't unique, you'll need to add other conditions to the ON clauses.
If you are just concerned about updating the bookid value from table2, you can change the value of bookid with the below query
UPDATE t1 SET t1.bookid = t2.bookid
FROM table1 t1
JOIN table2 t2 ON t1.id = t2.id
If you think your id column is not unique in two tables, you might need to consider adding other matching columns in the JOIN.

SQL Server stored procedure select, exists, multiple tables

Any method to do this?
Table1
1
2
3
4
5
Table2
3 (with the condition)
4 (without the condition)
I want to:
Select all records from Table1 if it exists in Table 2, where...(condition)
Select all records from Table1 if it not exists in Table2
Combine both select results. Sort all results with their created date.
For example, the result should be:
Result
1
2
3
5
Hopefully this can help.
SELECT t1.* from table1 t1
JOIN table2 t2
ON t1.ID = t2.ID
UNION ALL
SELECT t1.* from table1 t1 where ID in
(
SELECT t2.ID from table1 t1 except Select t2.ID from table2 t2
)
ORDER BY t1.CreatedDate
You can achieve this by doing:
SELECT t1.id
FROM Table1 t1
LEFT JOIN Table2 t2 on t1.id = t2.id
WHERE condition OR t2.id IS NULL
ORDER BY t1.CreatedDate;
See fiddle (I assumed condition to be t2.id!=4, but it can be anything else depending on other data in your tables).
There could be multiple solution.
One way
we can get the result set using two different queries and at last combine both of the result-set using UNION
Another way,
First statement is saying that get all the result set from TABLE1 if it exists in TABLE2 as well with some criteria (condition in where clause)
means using INNER JOIN we can achieve this
Second statement is saying get all the result set from TABLE1 which are not present in TABLE2
means along with INNER JOIN ed query also include the TABLE1's data if not present in TABLE2
here we can take the help of LEFT OUTER JOIN (taking TABLE1 on the left side)
Assumption: (condition: t1.Id != 4)
Let's try to understand the query using both of the above mentioned ways
---- -- --Step1 Create table and insert records
---- create table1 with Id int identity columsn
--CREATE TABLE Table1 (Id INT IDENTITY(1,1), CreatedDate smalldatetime default(getdate()));
--go
---- insert 1st 5 integers into Table1
--INSERT INTO Table1 DEFAULT VALUES
--go 5
---- create Table2 with Id int column
--CREATE TABLE Table2 (Id INT , CreatedDate smalldatetime default(getdate()));
--go
---- insert records 3,5 into Table2
--INSERT INTO Table2(Id) VALUES (3), (4);
-- -- -- Solution: one way
; WITH cteMyFirstResult AS
(
-- 2.1. Select all records from Table1 if it exists in Table 2, where...(condition)
SELECT
Id, CreatedDate
FROM Table1 AS t1
WHERE t1.Id IN (SELECT Id FROM Table2 AS t2)
AND t1.Id != 4 -- assumption it can be any condition
),cteMySecondResult AS (
-- 2.2. Select all records from Table1 if it not exists in Table2
SELECT
Id, CreatedDate
FROM Table1 AS t1 WHERE t1.Id NOT IN (SELECT Id FROM Table2 AS t2)
)
-- 2.3. Combine both select results. Sort all results with their created date.
SELECT
Id, CreatedDate
FROM cteMyFirstResult
UNION
SELECT
Id, CreatedDate
FROM cteMySecondResult
ORDER BY CreatedDate;
-- -- Solution: Another way (with bug)
SELECT t1.Id, t1.CreatedDate
FROM Table1 AS t1
LEFT JOIN Table2 AS t2 on t1.id = t2.id
WHERE t1.Id != 4
Order by T1.CreatedDate;
-- in this query we are using the criteria after doing the join operation.
-- thus after filtering out the result set based on JOIN Condition this condition will get applied
-- and if there is any null record in the Table1 for column Id (used in join) will not come in the final result-set
-- to avoid this we can include NULL check along with our criteria
-- -- Solution: Another way
SELECT t1.Id, t1.CreatedDate
FROM Table1 AS t1
LEFT JOIN Table2 AS t2 on t1.id = t2.id
WHERE ( t1.Id != 4 ) OR t1.Id IS NULL -- include all your criteria within small-barcket)
Order by T1.CreatedDate;
Thanks for all responses.
I come out with the answer I want:
SELECT *
FROM Table1 t1
WHERE NOT EXISTS(SELECT 1 FROM Table2 t2
WHERE t1.ID = t2.ID
AND t2.CIF_KEY = #CifKey
AND t2.STATUS <> ''3'')
AND (condition in where clause)

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