Saving a select count(*) value to an integer (SQL Server)

后端 未结 4 437
失恋的感觉
失恋的感觉 2021-02-01 05:41

I\'m having some trouble with this statement, owing no doubt to my ignorance of what is returned from this select statement:

declare @myInt as INT
set @myInt = (         


        
4条回答
  •  难免孤独
    2021-02-01 06:10

    If @myInt is zero it means no rows in the table: it would be NULL if never set at all.

    COUNT will always return a row, even for no rows in a table.

    Edit, Apr 2012: the rules for this are described in my answer here:Does COUNT(*) always return a result?

    Your count/assign is correct but could be either way:

    select @myInt = COUNT(*) from myTable
    set @myInt = (select COUNT(*) from myTable)
    

    However, if you are just looking for the existence of rows, (NOT) EXISTS is more efficient:

    IF NOT EXISTS (SELECT * FROM myTable)
    

提交回复
热议问题