In the below query, the columns GLName and GLDesc fetch the same value, but I need to have the same value with 2 different column names to satisfy the requirement of a predefined Excel template.
SELECT T0.GLCode, (SELECT ST0.Name From GL ST0 WHERE ST0.Code = T0.GLCode) AS GLName,
(SELECT ST0.Name FROM GL ST0 WHERE ST0.Code = T0.GLCode) AS GLDesc
FROM Trans T0
How can I reuse the result of the 1st subquery to avoid writing the 2nd subquery? This is a simplified example. In the real query, around 10 subqueries need to be reused in another subquery. In my case, it is difficult to build another table with all the required values from which to fetch the values in main query, as the master tables are huge and the values to be fetched from the master tables are only for specific codes which are based on the filtered records from the Trans table.
EDIT 1:
I am specifically asking about reuse of subquery. I do not want to use JOINs here because the real query with several JOINs takes around 60 seconds, whereas the query with subquery takes about 7-8 seconds. The only inconvenience is that I have to write the same subquery multiple times.
EDIT 2:
The query is inside a Stored Procedure, like this:
CREATE PROCEDURE [dbo].[My_Query_Proc]
AS
BEGIN
SELECT T0.GLCode, (SELECT ST0.Name From GL ST0 WHERE ST0.Code = T0.GLCode) AS GLName,
(SELECT ST0.Name FROM GL ST0 WHERE ST0.Code = T0.GLCode) AS GLDesc
FROM Trans T0
END
I prefer to use a single query in the Stored Procedure. I call this Stored Procedure from an Excel File in External Data command. I prefer to encapsulate it in Stored Procedure, instead of writing the query directly in Excel file.
If I try adding a variable:
DECLARE @GLName NVARCHAR(255)
and changing the query to:
SELECT T0.GLCode, @GLName = (SELECT ST0.Name From GL ST0 WHERE ST0.Code = T0.GLCode) AS GLName,
(SELECT ST0.Name FROM GL ST0 WHERE ST0.Code = T0.GLCode) AS GLDesc
FROM Trans T0
I get syntax error. Is there a way without using cursors or temp tables or writing procedural logic to fetch the result of 1st subquery into a variable, and use that variable's value for the column GLName as well as GLDesc?
My desired 'imaginary' query inside the SP is like this:
CREATE PROCEDURE [dbo].[My_Query_Proc]
AS
BEGIN
DECLARE @GLName NVARCHAR(255)
SELECT T0.GLCode, @GLName = (SELECT ST0.Name From GL ST0 WHERE ST0.Code = T0.GLCode) AS GLName,
@GLName AS GLDesc
FROM Trans T0
END
Is there any real query syntax corresponding to my imaginary query above?