How to check if a table variable is empty in SQL Server?

Eric Yin picture Eric Yin · Jan 5, 2012 · Viewed 31.1k times · Source

This is a section of one of my stored procedure:

@dataInTable dbo.Table_Variable readonly,
....

AND (
    ( @dataInTable IS NULL )
    OR
    ( item IN ( SELECT T FROM @dataInTable ) )
)

@dataInTable IS NULL is wrong in syntax, error is

Must declare the scalar variable "@dataInTable"

So I change it to:

(SELECT T FROM @dataInTable) IS NULL

This works but if @dataInTable has more than 1 item, I get an error:

Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >= or when the subquery is used as an expression.

Understandable, so I change it to:

(SELECT TOP(1) T FROM @ProgramRatings) IS NULL

Works perfectly, what I have is performance concern.

I am wondering, if there has an easier way to check whether a table variable is empty, like

AND (
    ( @dataInTable IS EMPTY )
    OR
    ( item IN ( SELECT T FROM @dataInTable ) )
)

Answer

Phil Klein picture Phil Klein · Jan 5, 2012

Table variables are different from scalar variables so @dataInTable IS NULL is not allowed as you mentioned. I would suggest the following:

EXISTS (SELECT 1 FROM @dataInTable)

The following also may make sense for your situation if you actually care to know the count:

DECLARE @dataCount int = (SELECT COUNT(1) FROM @dataInTable)
IF @dataCount = 0 -- Empty