Hi @Ajay Kamath ,
You can use cursor:
CREATE SCHEMA sch1;
CREATE SCHEMA sch2;
DROP TABLE if exists sch1.File1_table
CREATE TABLE sch1.File1_table ( [File_Version_ID] varchar(50), [Name] varchar(50), [Qty] varchar(50) )
INSERT INTO sch1.File1_table VALUES ( '101', 'aaa', '10' ),
( '101', 'bbb', '20' ),
( '101', 'ccc', '30' )
DROP TABLE if exists sch2.File2_table
CREATE TABLE sch2.File2_table ( [File_Version_ID] varchar(50), [Name] varchar(50), [Qty] varchar(50) )
INSERT INTO sch2.File2_table VALUES ( '102', 'ccc1', '300' ),
( '102', 'DDD1', '500' ),
( '102', 'FFFDDD1', 'FF500' )
DROP TABLE if exists ##temp
CREATE TABLE ##temp([Filename] varchar(20),count int)
DECLARE @EffectiveDate VARCHAR(50)
DECLARE @sql NVARCHAR(MAX)
SET @EffectiveDate='2021-10-05'
DECLARE mycursor CURSOR FOR
SELECT t1.[File Name],[File Version ID],CONCAT(t2.[Schema_Name],'.',t1.[Table Name]) [Table Name]
FROM [Table 1] t1
JOIN [Table 2] t2 ON t1.[Table Name]=t2.[Table Name]
WHERE [Effective Date] =@EffectiveDate
OPEN mycursor
DECLARE @filename VARCHAR(4000),@fileversionid NVARCHAR(4000),@TableName NVARCHAR(4000)
FETCH NEXT FROM mycursor INTO @filename,@fileversionid,@TableName
WHILE @@FETCH_STATUS=0
BEGIN
SET @sql= 'insert into ##temp select '''+@filename+''',count(*) from '+@TableName +' where [File_Version_ID]='+@fileversionid
EXECUTE sp_executesql @sql
FETCH NEXT FROM mycursor INTO @filename,@fileversionid,@TableName
END
CLOSE mycursor
DEALLOCATE mycursor
SELECT * FROM ##temp
Output:
It is worth noting that the cursor will affect performance.
If you have any question, please feel free to let me know.
Regards
Echo
If the answer is helpful, please click "Accept Answer" and upvote it.
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.