How can SQL Server determine if a query result is empty?

In SQL Server, you can use the following method to check if the query result is empty:

  1. Use the COUNT() function: Use the COUNT() function in a query statement to count the number of rows in the query result. If the number of rows is 0, it means the query result is empty.
SELECT COUNT(*) FROM 表名 WHERE 条件;
  1. Utilize EXISTS Subquery: Incorporate an EXISTS subquery in the query to determine if the query result exists, returning TRUE if it does, and FALSE if it doesn’t.
IF EXISTS (SELECT * FROM 表名 WHERE 条件)
    PRINT '查询结果不为空';
ELSE
    PRINT '查询结果为空';
  1. Use the @@ROWCOUNT variable: after executing a query statement, use the @@ROWCOUNT variable to retrieve the number of affected rows. If the row count is 0, it indicates that the query result is empty.
SELECT * FROM 表名 WHERE 条件;

IF @@ROWCOUNT > 0
    PRINT '查询结果不为空';
ELSE
    PRINT '查询结果为空';

Please note that the “table name” and “conditions” in the above methods need to be replaced according to the actual situation.

Leave a Reply 0

Your email address will not be published. Required fields are marked *


广告
Closing in 10 seconds
bannerAds