Thursday, May 9, 2013

SQL-Important Sql table Queries


1.how to check sql server version
Ans-select @@version

---------------------------------------
2.how to check how many tables
Ans-select * from sys.tables

-----------------------------------------
3.how to show complete structure of table
Ans-EXEC sp_help TableName;

-----------------------------------------
4.How to show all temp tables in sql server
Ans-select * from tempdb.sys.objects

---------------------------------------------
5.How to list all indexes
SELECT T.Name, I.name FROM sys.indexes I INNER JOIN Sys.tables t ON t.object_id = I.Object_ID WHERE index_id >= 1 -- skip heep

-------------------------------------------
6.How to list all indexes with all details
select * from sys.indexes

-------------------------------------------
7.How to get first and last date of month
DECLARE @Month int
DECLARE @Year int

set @Month = 2
set @Year = 2005

select DATEADD(month,@Month-1,DATEADD(year,@Year-1900,0)) /*First*/

select DATEADD(day,-1,DATEADD(month,@Month,DATEADD(year,@Year-1900,0))) /*Last*/


-----------------------------------------
8.Display every Nth row

Query:
SELECT id
FROM employees
GROUP BY id
HAVING MOD(id, N) = 0;

-------------------
9.Age in years

DECLARE @dob  datetime
SET @dob='1992-01-09 00:00:00'

SELECT DATEDIFF(hour,@dob,GETDATE())/8766.0 AS AgeYearsDecimal
    ,CONVERT(int,ROUND(DATEDIFF(hour,@dob,GETDATE())/8766.0,0)) AS AgeYearsIntRound
    ,DATEDIFF(hour,@dob,GETDATE())/8766 AS AgeYearsIntTrunc

----------------------------------------

10.Date diffrence

DATEDIFF(datepart,startdate,enddate)

-----------------------------------------
11.Update Table using Join

UPDATE employee e LEFT JOIN employee_salary s ON e.id=s.employee_id
SET s.salary='50000'
where e.first_name='Admin'

No comments:

Post a Comment

Your comment is pending for approval

AngularJS Basics - Part 1

                                                                  AngularJS What is AngularJS ·          Framework by googl...