我需要创建HEADER和TRAILER记录。 TRAILER需要包括“主要”查询的行数。如何获取查询的@@ Rowcount并将其保存到variable中,以包含在TRAILER中。
看到这个。
--- Var to save Count
declare @cnt int
-- HEADER RECORD
Select Cast('H' as Char(2)) +
Cast('MyFile' as Char(30))
+ CONVERT(Char(8),GetDate(),112)
union all
-- MAIN Query that I need the Count of
Select top 10 lastname from CUSTOMERS
set @cnt = @@ROWCOUNT
union all <--ERROR obviously
-- TRAILER record
Select Cast('T' as Char(2)) +
CONVERT(Char(9),GetDate(),112) +
Right(Replicate('0',9) + Cast(@cnt as VarChar(9)),9)
提前
答案 0 :(得分:2)
您可以使用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
答案 1 :(得分:1)
尝试以下脚本-
-- HEADER RECORD
SELECT CAST('H' AS CHAR(2)) + CAST('MyFile' AS CHAR(30)) + CONVERT(CHAR(8), GETDATE(), 112)
UNION ALL
-- MAIN Query that I need the Count of
SELECT lastname FROM CUSTOMERS
UNION ALL
-- TRAILER record
SELECT CAST('T' AS CHAR(2)) + CONVERT(CHAR(9), GETDATE(), 112) + RIGHT(REPLICATE('0', 9) + CAST(
(
SELECT COUNT(lastname) FROM CUSTOMERS
) AS VARCHAR(9)), 9);