Aug 9, 2016

Query to subtract in MongoDB

We can use $subtract operator to subtract tow numbers. $subtract is arithmetic aggregation operator which subtract two number and returns the difference.

$subtract can be use to get differences between dates means we can subtract date also, $subtract treat to second number as millisecond if first number is date type.

Syntax:


{ $subtract: [ <expression1>, <expression2> ] }


Example: Suppose we have a collection “Inventory” as below and before show the details of product on our website we need to calculate total price in our query.


{
            _id:1,
            Title:"Title1",
            SKU:"1234567890123",
            Price:20.50,
            ShippingCharge:4.80,
            Discount:2.00,
            CreatedDate:ISODate("2016-08-09T013:00:00Z")
}
{
            _id:2,
            Title:"Title2",
            SKU:"1234567890121",
            Price:30.50,
            ShippingCharge:4.80,
            Discount:2.00,
            CreatedDate:ISODate("2016-08-09T013:00:00Z")
}
{
            _id:3,
            Title:"Title3",
            SKU:"1234567890122",
            Price:50.50,
            ShippingCharge:4.80,
            Discount:2.00,
            CreatedDate:ISODate("2016-08-09T013:00:00Z")
}


See the following query here we calculating the discounted price. We are adding Price and ShippingCharge and subtract discounted price.


db.Inventory.aggregate(
[
            { $project:
                        { Title: 1,SKU:1, Discounted_Price:
                                    { $subtract:
                                                [ { $add: [ "$Price", "$ShippingCharge" ] }, "$Discount" ]
                                    }
                        }
            }
] )


Result:


/* 1 */
{
    "_id" : 1,
    "Title" : "Title1",
    "SKU" : "1234567890123",
    "Discounted_Price" : 23.3
}

/* 2 */
{
    "_id" : 2,
    "Title" : "Title2",
    "SKU" : "1234567890121",
    "Discounted_Price" : 33.3
}

/* 3 */
{
    "_id" : 3,
    "Title" : "Title3",
    "SKU" : "1234567890122",
    "Discounted_Price" : 53.3
}


Same like that if you want to subtract date you can use $subtract operator.

Subtract one day from CreatedDate
See following query which is subtracted one day from CreatedDate.


db.Inventory.aggregate(
[
            { $project:
                        { Title: 1,SKU:1, Sub_Date:
                                    { $subtract:
                                                [ "$CreatedDate", 24*60*60*1000 ]
                                    }
                        }
            }
] )


Result:


/* 1 */
{
    "_id" : 1,
    "Title" : "Title1",
    "SKU" : "1234567890123",
    "Sub_Date" : ISODate("2016-08-08T01:00:00.000Z")
}

/* 2 */
{
    "_id" : 2,
    "Title" : "Title2",
    "SKU" : "1234567890121",
    "Sub_Date" : ISODate("2016-08-08T01:00:00.000Z")
}

/* 3 */
{
    "_id" : 3,
    "Title" : "Title3",
    "SKU" : "1234567890122",
    "Sub_Date" : ISODate("2016-08-08T01:00:00.000Z")
}



Aug 8, 2016

How to get absolute value in MongoDB

To get absolute value we can use $abs operator. $abs is the arithmetic aggregate operator which returns absolute value of number.
Absolute value means it always returns positive value while number may positive or negative.

Before version of mongodb 3.2 we can’t use directly on number like below
{ $project: { number: { $abs: '$number } }  we needed some calculation as below.

db.Col.aggregate([
   {
     $project: { abs_value: { $abs: { $subtract: [ 1, 2 ] } } }
   }
]).

Syntax:


{ $abs: <number> }


Example: Run the following script which $subtract will return negative value but $abs will return absolute value of subtract.


db.Col.aggregate([
   {
     $project: { abs_value: { $abs: { $subtract: [ 1, 2 ] } } }
   }
])


OR

db.ratings.aggregate([
   {
     $project: { abs_value: { $abs: -1 } }
   }
])


It will return abs_value =1.0

Note: If argument field is missing or null it will return null.

{$abs:-1} result 1
{$abs:1} result 1

{$abs:null} result null

Aug 5, 2016

Shorthand way to return values that might be null

Problem: Suppose we have get-only property as below. In this we have a private variable and a public property both are list type.


        private List<User> _usr ;
        public List<User> lst
        {
            get
            {
                if (_usr == null)
                {
                    _usr = new List<User>();
                }

                return _usr;
            }
        }


How can I optimize this code or any shorthand way to write code of above scenario?

Answer: Yes we can, there are many way to write code in short to above code.


        private List<User> _usr ;
        public List<User> lst
        {
            get
            {
                _usr = _usr ?? new List<User>();
                return _usr;
            }
        }


Or


        private List<User> _usr ;
        public List<User> lst
        {
            get{return _usr ?? (new List<User>());}
        }


How to get name, data type and fields size of table in SQL Server

Sometimes we need to see the column details like name, data type and size, this article may help you to find the details of column is database table.
Suppose we have an”Inventory” table as below.


CREATE TABLE [dbo].[Inventory2](
            [ID] [bigint] IDENTITY(1,1) PRIMARY KEY NOT NULL,
            [Title] [varchar](500) NULL,
            [SKU] [varchar](20) NULL,
            [Price] [decimal](18, 2) NULL,
            [Created_Date] [datetime] NULL,
            [Updated_Date] [datetime] NULL,
)
GO


And we need to see the details of above table’s columns, run the following script it may help to find the details of table’s columns like Name, Data_Type, and Length.


SELECT column_name as 'COL_NAME', data_type as 'Data_Type',
Col_Length(table_name,column_name) as 'MAX_LENGTH'
FROM information_schema.columns
WHERE table_name = 'Inventory'


Result:
COL_NAME       Data_Type    MAX_LENGTH
-------------- ------------ ----------
ID                     bigint          8
Title                  varchar       500
SKU                  varchar       20
Price                 decimal       9
Created_Date    datetime      8
Updated_Date   datetime      8

Aug 4, 2016

Difference between function and stored procedure in SQL Server

Some basic difference between stored procedure and function is described below.

The main difference between stored procedure and function is Function must returns a value while stored procedure can or not this is optional. Function can have input parameter only while stored procedure can have both input/output parameters. Function can be called from stored procedures but stored procedures can’t call from function.

Function

Stored Procedure
Function must returns a value

In stored procedure it is optional
Function can have input parameter only
Stored procedure can have both input and output parameter s
Function can be called from procedure

Procedure can‘t be called from function
Function allows only select statement
Procedure allows DML statement(SELECT, INSERT, UPDATE, DELETE)
Function can use in SQL statement like WHERE/HAVING/SELECT

Procedure can’t be use in SQL statement like WHERE/HAVING/SELECT
Function can return table and can be treated as another row set. This can be use in joins with other tables.


Transaction can’t be implement

Transaction can be implement in stored procedure



Paging in SQL server 2012 stored procedure using OFFSET and FETCH

In this article we will learn about pagination using OFFSET and FETCH, OFFSET and FETCH is the new features of SQL Server 2012. In earlier version this feature is not available so was very difficult to implement paging in our procedures it also kill procedures performance.

Pagination is very easy in SQL Server 2012. New feature of SQL Server 2012(OFFSET and FETCH) is described below.

OFFSET: OFFSET skips the specific number of rows. The number can be zero or greater than zero.

FETCH: FETCH returns specific number of rows after processing the OFFSET clause. The number can be one or greater than one.

OFSET Syntax:


OFFSET { integer_constant | offset_row_count_expression } { ROW | ROWS }


FETCH Syntax:


FETCH { FIRST|NEXT } <rowcount expression> { ROW|ROWS } ONLY


Limitation of OFFSET and FETCH:
  1. If you are using OFFSET and FETCH, it’s mandatory to use ORDER BY clause.
  2. OFFSET is mandatory if you are using FETCH.
  3. In query expression you can’t use TOP with OFFSET and FETCH.
  4. You can’t use COUNT(*) in query expression with OFFSET and FETCH.


Example: Suppose we have a table “Inventory” which has some basic data and we want to apply pagination when fetching the records of inventory in our procedure.

Run the following query to create “Inventory” table with some dummy records.


CREATE TABLE Inventory(
       ID BIGINT IDENTITY(1,1) PRIMARY KEY
       ,Title VARCHAR(500)
       ,SKU VARCHAR(20)
       ,Price DECIMAL(18,2)
       ,Created_Date DATETIME
       ,Updated_Date DATETIME
)

DECLARE @cnt INT=1000
WHILE(@cnt>0)
BEGIN
       INSERT INTO Inventory(Title,SKU,Price,Created_Date,Updated_Date)
       SELECT 'Title'+CONVERT(VARCHAR(5),@cnt),'SKU'++CONVERT(VARCHAR(5),@cnt),
       10+@cnt,GETDATE(),GETDATE()
       SET @cnt=@cnt-1
END


Now see the following script which is implemented with pagination.


-- =============================================
-- Author:                     Dilip Kumar SIngh
-- Create date: 04,Aug 2016
-- Description: 
-- =============================================
CREATE PROCEDURE usp_GetInventory
            @Index INT=0,
            @PageSize INT= 20
AS
BEGIN 
            SET NOCOUNT ON;
            SELECT ID,Title,SKU,Price,Created_Date
            FROM Inventory ORDER BY ID ASC
            OFFSET (@PageSize)*(@Index) ROWS --Offset to skip specific number of rows
            FETCH NEXT @PageSize ROWS ONLY   --fetch to fetch specific number of rows
            SET NOCOUNT OFF;
END
GO


Now execute the procedure to passing variable @Index and @Page it will fetch records accordingly.
Suppose I want to get 10 records for page index 1 then I will execute procedure as below.

EXEC usp_GetInventory @index=0,@PageSize=10


Result:

Note: in @Index you will pass the grid index value which should be started from zero, so you will pass value like @index=grid_ index-1, if index value is 1, 2,3,4,5 … or if you want to pass index value as same from 1 then change the procedure for OFFSET as OFFSET @PageSize*(@Index-1). In @pageSize you will pass the value to display number of records in grid.