Вы можете использовать CTE для повторного использования определения основного запроса:
WITH Query AS (
SELECT top 10 lastname from CUSTOMERS
)
SELECT X.Result
FROM (
SELECT Cast('H' as Char(2)) + Cast('MyFile' as Char(30))
+ CONVERT(Char(8),GetDate(),112) AS Result, 1 AS Position
UNION ALL
SELECT *, 2 AS Position FROM Query
UNION ALL
Select Cast('T' as Char(2)) + CONVERT(Char(9),GetDate(),112) + Right(Replicate('0',9)
+ Cast((SELECT COUNT(*) FROM Query) as VarChar(9)),9) AS Result, 3 AS Position
) X ORDER BY X.Position
Однако CTE будет оцениваться дважды;если ваш запрос сложный и требует много времени, вы можете использовать временную таблицу:
SELECT TOP 10 lastname INTO #Temp FROM CUSTOMERS
SELECT X.Result
FROM (
SELECT Cast('H' as Char(2)) + Cast('MyFile' as Char(30))
+ CONVERT(Char(8),GetDate(),112) AS Result, 1 AS Position
UNION ALL
SELECT *, 2 AS Position FROM #Temp
UNION ALL
Select Cast('T' as Char(2)) + CONVERT(Char(9),GetDate(),112) + Right(Replicate('0',9)
+ Cast((SELECT COUNT(*) FROM #Temp) as VarChar(9)),9) AS Result, 3 AS Position
) X ORDER BY X.Position