Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 SQL Server 2005 Forums
 Transact-SQL (2005)
 Select Count of all records to variable

Author  Topic 

Planet_x
Starting Member

15 Posts

Posted - 2010-05-17 : 15:37:02
Ok this is really aggravating.. I swear I have done this before using the exact same syntax and i cannot get it to work, keeps giving me invalid syntax error. How the hell do I declare an integer variable properly and set it equals to the count of my records in a table, is it not like the following?

DECLARE @COUNTER INT(8)
SET @COUNTER = SELECT COUNT(*) FROM dbo.TariffTemp

tkizer
Almighty SQL Goddess

38200 Posts

Posted - 2010-05-17 : 15:41:16
DECLARE @COUNTER INT
SET @COUNTER = (SELECT COUNT(*) FROM dbo.TariffTemp)

I prefer to do it this way:

DECLARE @COUNTER INT
SELECT @COUNTER = COUNT(*)
FROM dbo.TariffTemp

Tara Kizer
Microsoft MVP for Windows Server System - SQL Server
http://weblogs.sqlteam.com/tarad/

Subscribe to my blog
Go to Top of Page

tkizer
Almighty SQL Goddess

38200 Posts

Posted - 2010-05-17 : 15:43:50
INT(8) is not valid. It's just INT, which is 4 bytes. Or BIGINT, which is 8 bytes.

Tara Kizer
Microsoft MVP for Windows Server System - SQL Server
http://weblogs.sqlteam.com/tarad/

Subscribe to my blog
Go to Top of Page

ms65g
Constraint Violating Yak Guru

497 Posts

Posted - 2010-05-18 : 05:36:48
What if in the table did dont exists any records? so:

DECLARE @Counter INT;
SELECT @Counter = COALESCE(SUM(1), 0)
FROM table_name;

Print @Counter

______________________
Go to Top of Page

tkizer
Almighty SQL Goddess

38200 Posts

Posted - 2010-05-18 : 13:26:16
You do not need to add COALESCE to the code as @COUNTER will be 0 if there aren't any records. What I posted is sufficient.

Tara Kizer
Microsoft MVP for Windows Server System - SQL Server
http://weblogs.sqlteam.com/tarad/

Subscribe to my blog
Go to Top of Page

ms65g
Constraint Violating Yak Guru

497 Posts

Posted - 2010-05-18 : 15:58:52
Oh you right, I was little mistake. I imagine MAX. Because if there are not records in the table SELECT MAX(i) FROM t will be NULL.

For example:
select isnull( (select max(id) from t), 1 )


______________________
Go to Top of Page
   

- Advertisement -