4

This should be pretty easy but for some reason I can't get the syntax right for SQL Server 2008

I need my variable to be true if a table has columns otherwise it should be false.

As of now I have this

DECLARE @LEHasSessions bit

set @LEhasSessions = ((SELECT COUNT(*) FROM @LEForSession) > 0)

which is obviously not compiling.

How should the syntax be in order to make it work?

3 Answers 3

6

SQL Server doesn't have boolean datatypes. Use CASE X THEN 1 ELSE 0 instead.

Also it is best to use EXISTS rather than COUNT here so it can stop processing after reading the first row (as opposed to counting all the rows in the table).

SET @LEHasSessions = CASE
                       WHEN EXISTS(SELECT *
                                   FROM   @LEForSession) THEN 1
                       ELSE 0
                     END 
Sign up to request clarification or add additional context in comments.

Comments

4

You can actually just set @LEHasSessions to the output from COUNT(*). The output will be truncated down to the maximum allowable value for the destination data type. So for a BIT, even a value of 522078 will truncate down to 1 and 0 will be 0.

Using (SELECT TOP 1 * FROM @LEForSession) rather than just selecting from the table directly is necessary to satisfy performance concerns as it cuts down logical reads from scanning the entire table to scanning just one record of one page of the table.

DECLARE @LEHasSessions BIT;

SELECT @LEhasSessions = COUNT(*) 
FROM (SELECT TOP 1 * FROM @LEForSession) a
;

PRINT @LEHasSessions;

3 Comments

@MartinSmith the execution plan agrees with you. Both your query and mine result in a table scan (since there is no index on this memory table) however yours results in 1 logical read whereas mine results in 13 (using Production.Product from Adventure Works 2012). I've done a little reading on this COUNT vs EXISTS concept since this comment and now have this committed for future coding practices.
@MartinSmith I was discussing this concept with a superior colleague today and discovered another way to get the same performance (per statics io) as your "IF EXISTS" query without having to sacrifice the syntax simplicity of my "COUNT(*)" query. I've edited my answer with the new solution. This code results in only 1 logical read as it also stops at 1 record rather than reading every page in the table.
Yes that will avoid the issue. Not sure I agree RE: Simplicity though. EXISTS seems a more natural way of expressing this to me.
0
select @LEhasSessions = case when COUNT(*) > 0 then 1 else 0 end 
FROM @LEForSession

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.