Posted by: rawbee May 15, 2008
SQL Problems n Tips
Login in to Rate this Post:     0       ?        

Tips 1 list all database sizes in megabytes:

EXEC sp_MSforeachdb @command1="select '?', 0.0078125 * sum(size) from ?..sysfiles"

Tips 2 list all the primary keys, including composite primary keys, in the AdventureWorks database:

USE AdventureWorks;

SELECT

TableName = o.name,

PrimaryKey = co.name,

Rows = i.rows

FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS c

INNER JOIN sysindexes i

ON c.constraint_name = i.name

and CONSTRAINT_TYPE = 'PRIMARY KEY'

INNER JOIN sysindexkeys k

ON i.id = k.id

AND i.indid = k.indid

INNER JOIN sys.columns co

ON i.id = co.object_id AND

k.colid = co.column_id

INNER JOIN sys.objects o

ON co.object_id = o.object_id

WHERE o.type = 'U'

AND i.rows > 0

order by TableName, PrimaryKey

Tips 3 How to find the nth highest price by color?

use AdventureWorks

select Color, ListPrice

from

(select Color,

ListPrice,

SequenceNo=row_number() over (partition by Color order by ListPrice desc)

from Production.Product

where ListPrice > 0)a

where SequenceNo=5

 

will be continue........

Read Full Discussion Thread for this article