March 25, 2010

Remove duplicate records in a table

CREATE TABLE dbo.authors
(
PK_Column INT IDENTITY,
Authorname VARCHAR(50)
)
GO

INSERT dbo.authors(Authorname)
SELECT 'Author1'
UNION ALL SELECT 'Author1'
UNION ALL SELECT 'Author1'
UNION ALL SELECT 'Author2'
UNION ALL SELECT 'Author2'
UNION ALL SELECT 'Author3'
UNION ALL SELECT 'Author3'
UNION ALL SELECT 'Author4'
GO
SELECT * FROM dbo.authors
Go
DELETE authors FROM authors a
LEFT OUTER JOIN
(
SELECT Authorname, pk_column = MIN(PK_Column)
FROM dbo.authors
GROUP BY Authorname
)tbl ON a.pk_column = tbl.pk_column
WHERE tbl.pk_column IS NULL

More details:
http://docs.google.com/View?id=ddwrnq4_3hg8gvfhp

March 5, 2010

Update column value from one table to another table

update TPD
Set TPD.ID=TSL.RId
from UpdateTableName as TPD
INNER JOIN GetDataTableName as TSL on TSL.SourceMessage=TPD.SourceMessage
where TPD.ID is null