May 12, 2010

Sql Server : list of tables which have no records in a database.

select distinct o.name as TableName, x.rowcnt as Table_RowCount
from sysobjects o
inner join sysindexes x
on o.id = x.id
where x.rowcnt = 0 and x.groupid = 1
and o.type = 'U'

May 6, 2010

Sql Server: Use "Order by" clause in View

create view vw_Name
as
SELECT top 100 percent * FROM tableName
order by 1 asc

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