Wednesday, January 21, 2009

Query to Get All the Tables From Database

SELECT * FROM information_schema.tables where table_type= 'BASE TABLE'
This Query will return TABLE_CATALOG, TABLE_SCHEMA ,TABLE_NAME and TABLE_TYPE

SELECT name FROM sysobjects where type ='U'
This Query will return Only TABLE_NAME

SELECT * FROM sys.Objects where type = 'U'
OR
SELECT * FROM sysObjects where Xtype='U'

for User Tables
Xtype = 'U'

for View
Xtype='V'

for procedures
Xtype='P'

for Scalar Functions
Xtype = 'FN'

This Query will return All the Values Regarding to the particular table.

You can change and use it for getting nth highest salary from Employee table as follows

SELECT TOP 1 salary
FROM (
SELECT DISTINCT TOP n salary
FROM employee
ORDER BY salary DESC) a
ORDER BY salary
Note:
where n > 1 (n is always greater than one)

Select 2nd Highest Salary

SELECT MAX(Salary) FROM Employee WHERE Salary <> (SELECT MAX(Salary) FROM Employee)

select MAX(Salary) from Employee where Salary!=(select MAX(Salary) from Employee)

Select MAX(Salary) From Employee where Salary not in ( Select MAX (Salary) From Employee)

SELECT TOP 1 Salary FROM (SELECT DISTINCT TOP 2 Salary FROM employee ORDER BY Salary DESC) a ORDER BY Salary

SELECT DISTINCT TOP 2 Salary FROM employee ORDER BY Salary DESC