In this Article, We are going to see how to join or relate or make connection between Non-related Tables In SQL Server.
Demo Table – SQL Script
IF OBJECT_ID('Tempdb..#T1') IS NOT NULL DROP TABLE #T1; CREATE TABLE #T1 (T1_Name VARCHAR(75)); INSERT INTO #T1 (T1_Name) VALUES ('Animal'),('Bat'),('Cat'),('Duet'); SELECT * FROM #T1;
IF OBJECT_ID('Tempdb..#T2') IS NOT NULL DROP TABLE #T2; CREATE TABLE #T2 (T2_Class VARCHAR(10)); INSERT INTO #T2 (T2_Class) VALUES ('Z'),('T'),('H'); SELECT * FROM #T2;
Demo Table – Table with Data
Joining Non-Related Tables
To Join Non-Related Tables , we are going to introduce one common joining column of Serial Numbers like below. To check how to Implement Serial Numbers Without Ordering Any of the Columns, Please check here.
SELECT T1.T1_Name,ISNULL(T2.T2_Class,'') AS T2_Class FROM ( SELECT T1_Name,ROW_NUMBER() OVER(ORDER BY (SELECT NULL)) AS S_NO FROM #T1) T1 LEFT JOIN ( SELECT T2_Class,ROW_NUMBER() OVER(ORDER BY (SELECT NULL)) AS S_NO FROM #T2) T2 ON t1.S_NO=T2.S_NO;
In this Article, we saw how to make Join between two Non-Related Tables in SQL Server. These Queries are unit tested with both On-Premises and Azure Sql db.