T-SQL how to identfiy tables that have dulicate roaws
How can I search the db and indentify the tables that have duplicate raws.
Thanks
CREATE TABLE Employee
(EmployeeId INT,
FirstName VARCHAR(50),
LastName VARCHAR(50))
SELECT EmployeeId, FirstName, LastName, count(*)
FROM Employee
GROUP BY EmployeeId, FirstName, LastName
HAVING count(*) <> 1
Looking for relevant Development Whitepapers? Visit the SearchWinDevelopment.com Research Library.
Mrdenny | Jun 17 2008 10:14PM GMT
Check out my SQL Server blog “SQL Server with Mr Denny” for more SQL Server information.
Techzon12 | Jun 18 2008 8:10PM GMT
*/ I have created the following query. It does the job in idenifying tables that have duplicate “Date_Stamp” id’s. I am working on improving it, so it will only display the tables with duplicate “date_stamp”. Right now it will output all table names. The ones that don’t have duplicates will show a null value. The ones with duplicates will display all the duplicate records.
*/
DECLARE @name_var varchar(50)
DECLARE @get_name CURSOR
– Define cursor - get all tables names
SET @get_name = CURSOR FOR
SELECT name
FROM dbo.sysobjects
WHERE xtype = ‘U’
– Open the cursor
OPEN @get_name
– Fetch the cursor into the declared variable
FETCH NEXT FROM @get_name INTO @name_var
WHILE (@@FETCH_STATUS = 0)
BEGIN
if exists ( select * from INFORMATION_SCHEMA.COLUMNS where TABLE_NAME= @name_var and COLUMN_NAME = ‘Date_Stamp’ )
Begin
select @name_var
execute (’select Date_Stamp from ‘ + @name_var + ‘ group by Date_Stamp having count (Date_Stamp) <>1′)
End
FETCH NEXT FROM @get_name INTO @name_var
END
– Cleanup
CLOSE @get_name
DEALLOCATE @get_name