Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check whether a table contains rows or not sql server 2005

How to Check whether a table contains rows or not sql server 2005?

like image 845
bala3569 Avatar asked Jan 27 '10 09:01

bala3569


People also ask

What does DBCC table check do?

Designed to provide a small overhead check of the physical consistency of the table, this check can also detect torn pages, and common hardware failures that can compromise data. A full run of DBCC CHECKTABLE may take considerably longer than in earlier versions.

What is DBCC in SQL?

Microsoft SQL Server Database Console Commands (DBCC) are used for checking database integrity; performing maintenance operations on databases, tables, indexes, and filegroups; and collecting and displaying information during troubleshooting issues.

How do you check the Contains in SQL?

Method 1 - Using CHARINDEX() function This function is used to search for a specific word or a substring in an overall string and returns its starting position of match. In case no word is found, then it will return 0 (zero).


2 Answers

For what purpose?

  • Quickest for an IF would be IF EXISTS (SELECT * FROM Table)...
  • For a result set, SELECT TOP 1 1 FROM Table returns either zero or one rows
  • For exactly one row with a count (0 or non-zero), SELECT COUNT(*) FROM Table
like image 61
gbn Avatar answered Oct 12 '22 21:10

gbn


Also, you can use exists

select case when exists (select 1 from table)            then 'contains rows'            else 'doesnt contain rows'         end 

or to check if there are child rows for a particular record :

select * from Table t1 where exists( select 1 from ChildTable t2 where t1.id = t2.parentid) 

or in a procedure

if exists(select 1 from table) begin  -- do stuff end 
like image 44
Mongus Pong Avatar answered Oct 12 '22 22:10

Mongus Pong