Hi @Avik Mukherjee ,
Welcome to Microsoft Q&A!
I created two tables including one external id column to store the two resultsets and another table Pair to store the final result.
Please refer below and check whether it is helpful to you.
--DDL
create table t1
(id int identity(1,1) ,
StudentID int,
StudentName varchar(20))
insert into t1 values
(1,'Johm'),
(2,'Patrick'),
(3,'Bob')
create table t2
(id int identity(1,1) ,
Dept varchar(20))
insert into t2 values
('Maths'),
('English')
create table Pair
(RowID int,
[Key] varchar(20),
[Value] varchar(20))
Then create one procedure as below:
create or alter procedure myprocedure (@TableName varchar(100))
as
begin
DECLARE @sql nVARCHAR(max), @max int
select @max=isnull(max(rowid),0) from pair
select @sql =''
select @sql = @sql+ ' Select id+'+cast(@max as char(2))+','''+ [name] +' '' [key], cast(' + [name] + ' as nvarchar(10)) [Value] from ' +@TableName + ' union '
from sys.columns where object_name (object_id) = @TableName and [name]<>'id'
set @sql = SUBSTRING(@sql,1,len(@sql)-5) + ' order by id+'+cast(@max as char(2))
insert into Pair
exec(@sql)
end
Then execute this procedure as below:
exec myprocedure 't1'
exec myprocedure 't2'
Finally query the Pair table:
select * from Pair
Output:
RowID Key Value
1 StudentID 1
1 StudentName Johm
2 StudentID 2
2 StudentName Patrick
3 StudentID 3
3 StudentName Bob
4 Dept Maths
5 Dept English
Best regards,
Melissa
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.