Storm
Storm

Reputation: 2022

Get aliased table names from SQL Query

Given the following table:

CREATE TABLE #TestTable
(
    Code varchar(10) NOT NULL,
    Parent varchar(10) NULL
);

INSERT INTO #TestTable
SELECT 'Parent', Null UNION ALL
SELECT 'Child', 'Parent';

I want to be able to convert this:

SELECT * 
FROM #TestTable child
INNER JOIN #TestTable parent ON ( parent.Code = child.Parent );

into this:

SELECT child.Code, child.Parent, parent.Code, parent.Parent
FROM #TestTable child
INNER JOIN #TestTable parent ON ( parent.Code = child.Parent );

Using sp_describe_first_result_set I can get close by using this statement:

EXEC sp_describe_first_result_set
N'SELECT * 
FROM #TestTable child
INNER JOIN #TestTable parent ON ( parent.Code = child.Parent )', NULL, 2;

but it'll return the source table as #TestTable instead of child/parent.

Upvotes: 2

Views: 970

Answers (1)

Dwight Reynoldson
Dwight Reynoldson

Reputation: 960

If the only thing you care about is looking at which table is the source table you could split the data in to 2 temporary tables, that way you will affect the source_table returned by your system stored procedure call.

CREATE TABLE #TestTable
(
    Code varchar(10) NOT NULL,
    Parent varchar(10) NULL
);

INSERT INTO #TestTable
SELECT 'Parent', Null UNION ALL
SELECT 'Child', 'Parent';

select * into #Parent from #TestTable where code='Parent';

select * into #Child from #TestTable where Code='Child';

EXEC sp_describe_first_result_set
N'SELECT * 
FROM #Child child
INNER JOIN #Parent parent ON ( parent.Code = child.Parent )', NULL, 2;


drop table #TestTable, #Parent, #Child;

enter image description here

Upvotes: 1

Related Questions