Sunday, September 2, 2018

Date Function : DATEDIFF()

This is used to find the difference between two dates based on DatePart type
The DATEDIFF() function returns the time between two dates.

Syntax:
DATEDIFF(DatePart,StartDate,EndDate)

DatePart is Abbreviation used same as in DatePart() function.
StartDate and EndDate are valid date time.

Example:

SELECT DATEDIFF(day,'2015-01-23 10:00:44.470','2015-10-23 10:00:44.470') AS DiffDate

--The Difference between millisecond, nanosecond and microsecond should be less otherwise it will throw below error.

Msg 535, Level 16, State 0, Line 1
The datediff function resulted in an overflow. The number of dateparts separating two date/time instances is too large. Try to use datediff with a less precise datepart.

SELECT DATEDIFF(millisecond,'2015-10-23 10:00:43.470','2015-10-23 10:00:44.470') AS DiffDate

OutPut:

DatePart
Type
Return Value
year
yy, yyyy
1
quarter
qq, q
7
month
mm, m
21
dayofyear
dy, y
638
day
dd, d
638
week
wk, ww
91
weekday
dw, w
638
hour
hh
15312
minute
mi, n
918720
second
ss, s
55123200
millisecond
ms
100
microsecond
mcs
1000000
nanosecond
ns
1000000000

Monday, August 27, 2018

Sum Comma Separated values in SQL Server

Scenario: Comma Separated values are stored in a single column.
Need to show the output summation of values in single column.

Here is the expected Before/After:


Table structure:

create table SumCommaSeparated
(
  id int identity(1,1),
  value varchar(200)
)

Insert Values into table:

insert into SumCommaSeparated values('20,12,14,34');
insert into SumCommaSeparated values('20,15,14,34,82,90');
insert into SumCommaSeparated values('200');

Create SQL function to sum up and show the output:

Create FUNCTION [dbo].[fnSplit]
(
@list  NVARCHAR(2000)

RETURNS TABLE AS
RETURN

   WITH SplitRecords(LoopStart, LoopEnd) AS (
--Split Column values till End
     SELECT LoopStart = 1,
        LoopEnd = CHARINDEX(',' COLLATE Latin1_General_CI_AS, @list + ',')
     UNION ALL
     SELECT LoopStart = LoopEnd + 1,
            LoopEnd = CHARINDEX(',' COLLATE Latin1_General_CI_AS,@list + ',', LoopEnd + 1)

     FROM   SplitRecords
WHERE  LoopEnd > 0
  )
  SELECT sum(cast(LTRIM(RTRIM(SUBSTRING(@list, SplitRecords.LoopStart,
CASE WHEN SplitRecords.LoopEnd > 0 THEN SplitRecords.LoopEnd - SplitRecords.LoopStart ELSE 0 END))) as bigint)) 
--Cast your output according to requirement
AS VALUE
  FROM   SplitRecords
  WHERE  LoopEnd > 0


SQL Script:

select SCSep.id,SCSep.value BeforeAddition,fn.VALUE as AfterAddition
from SumCommaSeparated SCSep
cross apply [dbo].[fnSplit](SCSep.value) as fn