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:
- 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 条件;
- 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 '查询结果为空';
- 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.