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
 General SQL Server Forums
 Script Library
 Script: Find tables without primary keys

Author  Topic 

aiken
Aged Yak Warrior

525 Posts

Posted - 2002-08-03 : 16:18:12
...got tired of looking at them by hand.

Cheers
-b

DECLARE @vcDB varchar(20),@vcSchema varchar(20),@vcTable varchar(200)

Select @vcDB='mydb',@vcSchema='dbo'

DECLARE cLoop cursor for
select TABLE_NAME
from INFORMATION_SCHEMA.TABLES
where TABLE_CATALOG=@vcDB
and TABLE_SCHEMA=@vcSchema
order by TABLE_NAME ASC

open cLoop

FETCH NEXT FROM cLoop INTO @vcTable
WHILE @@FETCH_STATUS=0
BEGIN
if not exists (SELECT *
FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS
WHERE TABLE_SCHEMA = @vcSchema
AND TABLE_NAME = @vcTable
AND CONSTRAINT_TYPE = 'PRIMARY KEY')
print @vcTable + ' does not have a primary key'

FETCH NEXT FROM cLoop INTO @vcTable
END
Close cLoop
DEALLOCATE cLoop


jasper_smith
SQL Server MVP & SQLTeam MVY

846 Posts

Posted - 2002-08-03 : 17:18:52
Non cursor way SQL7 & SQL2000

select TABLE_NAME from INFORMATION_SCHEMA.TABLES
where OBJECTPROPERTY(OBJECT_ID(TABLE_NAME),'TableHasPrimaryKey')=0



HTH
Jasper Smith
Go to Top of Page

aiken
Aged Yak Warrior

525 Posts

Posted - 2002-08-04 : 04:08:42
Lol. Fine, be a wise guy.

Thanks... that is much better. Didn't know about that property.
-b

Go to Top of Page
   

- Advertisement -