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

后端 未结 4 474
失恋的感觉
失恋的感觉 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 05:58

    Declare @MyInt int
    Set @MyInt = ( Select Count(*) From MyTable )
    
    If @MyInt > 0
    Begin
        Print 'There''s something in the table'
    End
    

    I'm not sure if this is your issue, but you have to esacpe the single quote in the print statement with a second single quote. While you can use SELECT to populate the variable, using SET as you have done here is just fine and clearer IMO. In addition, you can be guaranteed that Count(*) will never return a negative value so you need only check whether it is greater than zero.

提交回复
热议问题