Tuesday, 13 May 2014

DATE INCREASE AND DECREASE LIKE ONE MONTH, WEEK AND DAY IN SQL SERVER

Query :  Incrementing datepart by an interval of 1



SELECT 'week',DATEADD(week,1,getdate())   ---- Add one week

SELECT 'month',DATEADD(month,1,getdate()) ---- Add one month

SELECT 'day',DATEADD(day,1,getdate())  ---- Add one day


Query :  Decrementing datepart by an interval of 1



SELECT 'week',DATEADD(week,-1,getdate())   ---- Minus one week

SELECT 'month',DATEADD(month,-1,getdate()) ---- Minus one month

SELECT 'day',DATEADD(day,-1,getdate())  ---- Minus one day

DATEDIFF in Sql Server

Returns the count (signed integer) of the specified datepart boundaries crossed between the specified startdate and enddate.

Syntax

DATEDIFF ( datepart , startdate , enddate )

Arguments

datepart
Is the part of startdate and enddate that specifies the type of boundary crossed. The following table lists all valid datepart arguments. User-defined variable equivalents are not valid.
datepart
Abbreviations
year
yy, yyyy
quarter
qq, q
month
mm, m
dayofyear
dy, y
day
dd, d
week
wk, ww
hour
hh
minute
mi, n
second
ss, s
millisecond
ms
microsecond
mcs
nanosecond
ns
startdate
Is an expression that can be resolved to a timedatesmalldatetimedatetimedatetime2, or datetimeoffset value. date can be an expression, column expression, user-defined variable or string literal. startdate is subtracted from enddate.
To avoid ambiguity, use four-digit years. For information about two digits years, see Configure the two digit year cutoff Server Configuration Option.
enddate
See startdate.

Return Value

Each datepart and its abbreviations return the same value.
If the return value is out of range for int (-2,147,483,648 to +2,147,483,647), an error is returned. For millisecond, the maximum difference between startdateand enddate is 24 days, 20 hours, 31 minutes and 23.647 seconds. For second, the maximum difference is 68 years.
If startdate and enddate are both assigned only a time value and the datepart is not a time datepart, 0 is returned.
A time zone offset component of startdate or endate is not used in calculating the return value.
Because smalldatetime is accurate only to the minute, when a smalldatetime value is used for startdate or enddate, seconds and milliseconds are always set to 0 in the return value.
If only a time value is assigned to a variable of a date data type, the value of the missing date part is set to the default value: 1900-01-01. If only a date value is assigned to a variable of a time or date data type, the value of the missing time part is set to the default value: 00:00:00. If either startdate or enddate have only a time part and the other only a date part, the missing time and date parts are set to the default values.
If startdate and enddate are of different date data types and one has more time parts or fractional seconds precision than the other, the missing parts of the other are set to 0.

datepart Boundaries

The following statements have the same startdate and the same endate. Those dates are adjacent and differ in time by .0000001 second. The difference between the startdate and endate in each statement crosses one calendar or time boundary of its datepart. Each statement returns 1. If different years are used for this example and if both startdate and endate are in the same calendar week, the return value for week would be 0.
SELECT DATEDIFF(year, '2005-12-31 23:59:59.9999999'
, '2006-01-01 00:00:00.0000000');
SELECT DATEDIFF(quarter, '2005-12-31 23:59:59.9999999'
, '2006-01-01 00:00:00.0000000');
SELECT DATEDIFF(month, '2005-12-31 23:59:59.9999999'
, '2006-01-01 00:00:00.0000000');
SELECT DATEDIFF(dayofyear, '2005-12-31 23:59:59.9999999'
, '2006-01-01 00:00:00.0000000');
SELECT DATEDIFF(day, '2005-12-31 23:59:59.9999999'
, '2006-01-01 00:00:00.0000000');
SELECT DATEDIFF(week, '2005-12-31 23:59:59.9999999'
, '2006-01-01 00:00:00.0000000');
SELECT DATEDIFF(hour, '2005-12-31 23:59:59.9999999'
, '2006-01-01 00:00:00.0000000');
SELECT DATEDIFF(minute, '2005-12-31 23:59:59.9999999'
, '2006-01-01 00:00:00.0000000');
SELECT DATEDIFF(second, '2005-12-31 23:59:59.9999999'
, '2006-01-01 00:00:00.0000000');
SELECT DATEDIFF(millisecond, '2005-12-31 23:59:59.9999999'
, '2006-01-01 00:00:00.0000000');

Remarks

DATEDIFF can be used in the select list, WHERE, HAVING, GROUP BY and ORDER BY clauses.
DATEDIFF implicitly casts string literals as a datetime2 type. This means that DATEDIFF does not support the format YDM when the date is passed as a string. You must explicitly cast the string to a datetime or smalldatetime type to use the YDM format.
Specifying SET DATEFIRST has no effect on DATEDIFF. DATEDIFF always uses Sunday as the first day of the week to ensure the function is deterministic.

Examples

The following examples use different types of expressions as arguments for the startdate and enddate parameters.

A. Specifying columns for startdate and enddate

The following example calculates the number of day boundaries that are crossed between dates in two columns in a table.
CREATE TABLE dbo.Duration
    (
    startDate datetime2
    ,endDate datetime2
    );
INSERT INTO dbo.Duration(startDate,endDate)
    VALUES('2007-05-06 12:10:09','2007-05-07 12:10:09');
SELECT DATEDIFF(day,startDate,endDate) AS 'Duration'
FROM dbo.Duration;
-- Returns: 1

B. Specifying user-defined variables for startdate and enddate

The following example uses user-defined variables as arguments for startdate and enddate.
DECLARE @startdate datetime2 = '2007-05-05 12:10:09.3312722';
DECLARE @enddate datetime2 = '2007-05-04 12:10:09.3312722'; 
SELECT DATEDIFF(day, @startdate, @enddate);

C. Specifying scalar system functions for startdate and enddate

The following example uses scalar system functions as arguments for startdate and enddate.
SELECT DATEDIFF(millisecond, GETDATE(), SYSDATETIME());

D. Specifying scalar subqueries and scalar functions for startdate and enddate

The following example uses scalar subqueries and scalar functions as arguments for startdate and enddate.
USE AdventureWorks2012;
GO
SELECT DATEDIFF(day,(SELECT MIN(OrderDate) FROM Sales.SalesOrderHeader),
    (SELECT MAX(OrderDate) FROM Sales.SalesOrderHeader));

E. Specifying constants for startdate and enddate

The following example uses character constants as arguments for startdate and enddate.
SELECT DATEDIFF(day, '2007-05-07 09:53:01.0376635'
    , '2007-05-08 09:53:01.0376635');

F. Specifying numeric expressions and scalar system functions for enddate

The following example uses a numeric expression, (GETDATE ()+ 1), and scalar system functions, GETDATE and SYSDATETIME, as arguments for enddate.
USE AdventureWorks2012;
GO
SELECT DATEDIFF(day, '2007-05-07 09:53:01.0376635', GETDATE()+ 1) 
    AS NumberOfDays
FROM Sales.SalesOrderHeader;
GO
USE AdventureWorks2012;
GO
SELECT DATEDIFF(day, '2007-05-07 09:53:01.0376635', DATEADD(day,1,SYSDATETIME())) AS NumberOfDays
FROM Sales.SalesOrderHeader;
GO

G. Specifying ranking functions for startdate

The following example uses a ranking function as an argument for startdate.
USE AdventureWorks2012;
GO
SELECT p.FirstName, p.LastName
    ,DATEDIFF(day,ROW_NUMBER() OVER (ORDER BY 
        a.PostalCode),SYSDATETIME()) AS 'Row Number'
FROM Sales.SalesPerson s 
    INNER JOIN Person.Person p 
        ON s.BusinessEntityID = p.BusinessEntityID
    INNER JOIN Person.Address a 
        ON a.AddressID = p.BusinessEntityID
WHERE TerritoryID IS NOT NULL 
    AND SalesYTD <> 0;

H. Specifying an aggregate window function for startdate

The following example uses an aggregate window function as an argument for startdate.
USE AdventureWorks2012;
GO
SELECT soh.SalesOrderID, sod.ProductID, sod.OrderQty,soh.OrderDate
    ,DATEDIFF(day,MIN(soh.OrderDate) 
        OVER(PARTITION BY soh.SalesOrderID),SYSDATETIME() ) AS 'Total'
FROM Sales.SalesOrderDetail sod
    INNER JOIN Sales.SalesOrderHeader soh
        ON sod.SalesOrderID = soh.SalesOrderID
WHERE soh.SalesOrderID IN(43659,58918);
GO

DATEADD in Sql Server

Returns a specified date with the specified number interval (signed integer) added to a specified datepart of that date.


Syntax

DATEADD (datepart , number , date )

Arguments

datepart
Is the part of date to which an integer number is added. The following table lists all valid datepart arguments. User-defined variable equivalents are not valid.
datepart
Abbreviations
year
yy , yyyy
quarter
qq , q
month
mm , m
dayofyear
dy , y
day
dd , d
week
wk , ww
weekday
dw , w
hour
hh
minute
mi , n
second
ss , s
millisecond
ms
microsecond
mcs
nanosecond
ns
number
Is an expression that can be resolved to an int that is added to a datepart of date. User-defined variables are valid.
If you specify a value with a decimal fraction, the fraction is truncated and not rounded.
date
Is an expression that can be resolved to a timedatesmalldatetimedatetimedatetime2, or datetimeoffset value. date can be an expression, column expression, user-defined variable, or string literal. If the expression is a string literal, it must resolve to a datetime. To avoid ambiguity, use four-digit years. For information about two-digit years, see Configure the two digit year cutoff Server Configuration Option.

Return Types

The return data type is the data type of the date argument, except for string literals.
The return data type for a string literal is datetime. An error will be raised if the string literal seconds scale is more than three positions (.nnn) or contains the time zone offset part.

datepart Argument

dayofyear , day, and weekday return the same value.
Each datepart and its abbreviations return the same value.
If datepart is month and the date month has more days than the return month and the date day does not exist in the return month, the last day of the return month is returned. For example, September has 30 days; therefore, the two following statements return 2006-09-30 00:00:00.000:
SELECT DATEADD(month, 1, '2006-08-30');
SELECT DATEADD(month, 1, '2006-08-31');
The number argument cannot exceed the range of int. In the following statements, the argument for number exceeds the range of int by 1. The following error message is returned: "Msg 8115, Level 16, State 2, Line 1. Arithmetic overflow error converting expression to data type int."
SELECT DATEADD(year,2147483648, '2006-07-31');
SELECT DATEADD(year,-2147483649, '2006-07-31');
The date argument cannot be incremented to a value outside the range of its data type. In the following statements, the number value that is added to the datevalue exceeds the range of the date data type. The following error message is returned: "Msg 517, Level 16, State 1, Line 1 Adding a value to a 'datetime' column caused overflow."
SELECT DATEADD(year,2147483647, '2006-07-31');
SELECT DATEADD(year,-2147483647, '2006-07-31');
The seconds part of a smalldatetime value is always 00. If date is smalldatetime, the following apply:
  • If datepart is second and number is between -30 and +29, no addition is performed.
  • If datepart is second and number is less than-30 or more than +29, addition is performed beginning at one minute.
  • If datepart is millisecond and number is between -30001 and +29998, no addition is performed.
  • If datepart is millisecond and number is less than -30001 or more than +29998, addition is performed beginning at one minute.

Remarks

DATEADD can be used in the SELECT <list>, WHERE, HAVING, GROUP BY and ORDER BY clauses.

Fractional Seconds Precision

Addition for a datepart of microsecond or nanosecond for date data types smalldatetimedate, and datetime is not allowed.
Milliseconds have a scale of 3 (.123), microseconds have a scale of 6 (.123456), And nanoseconds have a scale of 9 (.123456789). The timedatetime2, anddatetimeoffset data types have a maximum scale of 7 (.1234567). If datepart is nanosecondnumber must be 100 before the fractional seconds of dateincrease. A number between 1 and 49 is rounded down to 0 and a number from 50 to 99 is rounded up to 100.
The following statements add a datepart of millisecondmicrosecond, or nanosecond.
DECLARE @datetime2 datetime2 = '2007-01-01 13:10:10.1111111';
SELECT '1 millisecond', DATEADD(millisecond,1,@datetime2)
UNION ALL
SELECT '2 milliseconds', DATEADD(millisecond,2,@datetime2)
UNION ALL
SELECT '1 microsecond', DATEADD(microsecond,1,@datetime2)
UNION ALL
SELECT '2 microseconds', DATEADD(microsecond,2,@datetime2)
UNION ALL
SELECT '49 nanoseconds', DATEADD(nanosecond,49,@datetime2)
UNION ALL
SELECT '50 nanoseconds', DATEADD(nanosecond,50,@datetime2)
UNION ALL
SELECT '150 nanoseconds', DATEADD(nanosecond,150,@datetime2);
Here is the result set.
1 millisecond     2007-01-01 13:10:10.1121111
2 milliseconds    2007-01-01 13:10:10.1131111
1 microsecond     2007-01-01 13:10:10.1111121
2 microseconds    2007-01-01 13:10:10.1111131
49 nanoseconds    2007-01-01 13:10:10.1111111
50 nanoseconds    2007-01-01 13:10:10.1111112
150 nanoseconds   2007-01-01 13:10:10.1111113

Find Duplicate Column's Records And Delete Duplicate Records in Sql Server

Query : Find Duplicate Record From Table


select EmpSalary, count(*) TotalCount from Employee
group by EmpSalary having count(*) > 1 order by count(*) asc




Query : Delete Duplicate Record From Table



delete Employee where EmpId NOT IN
(select MIN(EmpId) from Employee group by EmpSalary)

Find Any Number Of Employee Salary ( Highest and Smallest) in Sql Server

Query :  Third Highest Employee Salary

select min(EmpSalary) from Employee where EmpSalary IN
(select Top 3 EmpSalary from Employee order by EmpSalary desc)



Query :  Third Smallest Employee Salary

select max(EmpSalary) from Employee where EmpSalary IN
(select Top 3 EmpSalary from Employee order by EmpSalary asc)

Union vs. Union All – Which is better for performance

UNION
The UNION command is used to select related information from two tables, much like the JOIN command. However, when using the UNION command all selected columns need to be of the same data type. With UNION, only distinct values are selected.
UNION ALL
The UNION ALL command is equal to the UNION command, except that UNION ALL selects all values.
The difference between Union and Union all is that Union all will not eliminate duplicate rows, instead it just pulls all rows from all tables fitting your query specifics and combines them into a table.
A UNION statement effectively does a SELECT DISTINCT on the results set. If you know that all the records returned are unique from your union, use UNION ALL instead, it gives faster results.
Example: 
Table 1 : First,Second,Third,Fourth,Fifth
Table 2 : First,Second,Fifth,Sixth
Result Set:
UNION: First,Second,Third,Fourth,Fifth,Sixth (This will remove duplicate values)
UNION ALL: First,First,Second,Second,Third,Fourth,Fifth,Fifth,Sixth,Sixth (This will repeat values)