25 pts.
 T-SQL how to identfiy tables that have dulicate roaws
I have a MS 2000 SQL server. How can I search the db and indentify the tables that have duplicate raws. Thanks

Software/Hardware used:
ASKED: June 17, 2008  9:44 PM
UPDATED: June 18, 2008  8:10 PM

Answer Wiki:
There is no generic script which can be used for this. You need to query each table to see if it has duplicate rows in it. If your table looked like this: <pre>CREATE TABLE Employee (EmployeeId INT, FirstName VARCHAR(50), LastName VARCHAR(50))</pre> And you wanted to check for duplicate records you would use this query to identify the duplicate rows. <pre>SELECT EmployeeId, FirstName, LastName, count(*) FROM Employee GROUP BY EmployeeId, FirstName, LastName HAVING count(*) <> 1</pre>
Last Wiki Answer Submitted:  June 17, 2008  10:14 pm  by  Denny Cherry   64,520 pts.
All Answer Wiki Contributors:  Denny Cherry   64,520 pts.
To see all answers submitted to the Answer Wiki: View Answer History.


Discuss This Question:
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _


 

Check out my SQL Server blog “SQL Server with Mr Denny” for more SQL Server information.

 64,520 pts.

 

*/ 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

 25 pts.