不显示空 select 结果

Don't display empty select results

我有一个 T-SQL 脚本可以执行许多 select 语句。大多数时候这些语句不会 return 任何东西,所以输出显示如下:

script results.

如果结果为空,有没有办法不显示 select 的 headers?

您可以 select 到 #temp table 中,如果您插入任何行,则只能从中 select 。

SELECT <cols> INTO #a
  FROM dbo.somewhere
  WHERE …;

If @@ROWCOUNT > 0
BEGIN
  SELECT <cols> FROM #a;
END

SELECT <cols> INTO #b
  FROM dbo.somewhere_else
  WHERE …;

If @@ROWCOUNT > 0
BEGIN
  SELECT <cols> FROM #b;
END

…

或者如果所有结果集都相同,您可以这样做:

DECLARE @rc int = 0;

SELECT <cols> INTO #a
  FROM dbo.somewhere
  WHERE …;

SET @rc += @@ROWCOUNT;

SELECT <cols> INTO #b
  FROM dbo.somewhere_else
  WHERE …;

SET @rc += @@ROWCOUNT;

...

IF @rc > 0
BEGIN
  SELECT <cols> FROM #a
  UNION ALL
  SELECT <cols> FROM #b
  UNION ALL
  ...;
END

甚至:

SELECT <cols> INTO #x FROM 
(
  SELECT <cols> FROM dbo.somewhere
  UNION ALL
  SELECT <cols> FROM dbo.somewhere_else
  UNION ALL
  ...
) AS x;

IF @@ROWCOUNT > 0
BEGIN
  SELECT <cols> FROM #x;
END

如果您需要知道哪 table 行来自:

SELECT <cols> INTO #x FROM 
(
  SELECT src = 'somewhere', <cols> FROM dbo.somewhere
  UNION ALL
  SELECT src = 'somewhere_else', <cols> FROM dbo.somewhere_else
  ...
) AS x;

IF @@ROWCOUNT > 0
BEGIN
  SELECT src, <cols> FROM #x;
END