My Blog List

LOVE IS LIFE

#htmlcaption1 #htmlcaption2 Stay Connected

Pages

Tuesday, October 1, 2013

SQL 2008 trim leading space, white space, tab

CREATE FUNCTION dbo.LTrimX(@str VARCHAR(MAX)) RETURNS VARCHAR(MAX)
AS
BEGIN
DECLARE @trimchars VARCHAR(10)
SET @trimchars = CHAR(9)+CHAR(10)+CHAR(13)+CHAR(32)
IF @str LIKE '[' + @trimchars + ']%' SET @str = SUBSTRING(@str, PATINDEX('%[^' + @trimchars + ']%', @str), 8000)
RETURN @str
END
GO
CREATE FUNCTION dbo.RTrimX(@str VARCHAR(MAX)) RETURNS VARCHAR(MAX)
AS
BEGIN
DECLARE @trimchars VARCHAR(10)
SET @trimchars = CHAR(9)+CHAR(10)+CHAR(13)+CHAR(32)
IF @str LIKE '%[' + @trimchars + ']'
SET @str = REVERSE(dbo.LTrimX(REVERSE(@str)))
RETURN @str
END
GO
CREATE FUNCTION dbo.TrimX(@str VARCHAR(MAX)) RETURNS VARCHAR(MAX)
AS
BEGIN
RETURN dbo.LTrimX(dbo.RTrimX(@str))
END
GO
/* Run the created function */
SELECT dbo.TRIMX('         word leading trailing spaces           ') AS 'TrimmedWord'
GO

http://youtu.be/1iVZFeL7IOE

Thursday, September 5, 2013

A beautiful morning in Bangalore

A Beautiful Morning in Bangalore

It was a beautiful morning in Bangalore. My name is Neha and I was lying on the bed and looking outside of the window. I saw a beautiful tree with purple flowers and sun shining brightly. I closed my eyes and I heard somebody shouting. I looked through the window and tried to identify what the commotion was all about. I saw my brother four years younger to me, amidst all of these confusion and chaos down below. As my parents were out of country it was me to take care of him. As I reached outside my house I came to know last night my brother had an accident while driving car with an auto driver and the auto driver trailed him since then and reached my house and demanded money. I yelled to my brother "Yeh sab log kuch bhi kar sakte hai paise ke liye, Paise de doh aur ghar ke andar aa jao"(These drivers can do anything for money, give them the money and come inside). He did as I said.

While serving him breakfast I asked him "what was the matter with the auto driver?” He replied that it was not his fault while narrating the entire story. My brother had boozed the previous night with his friends and had a small accident. I loved my brother a lot, just told him not to worry, he smiled back and we returned to our normal daily chores. I could see he was happy as I didn’t scold him for this entire matter and I love to see those smiles on his face.

It was December 14th, tomorrow is my best friend Tyagi’s birthday. We all friends planned to have the birthday celebration at my friend Sneha’s farmhouse. Lots of things to do and time was less. But finally we made all our arrangements. We all friends gathered together and right at midnight Tyagi cut the cake and party began. It was 2:00am all had lots of fun and were prepared to leave. I called up my brother to pick me up. On the way back to our home I was explaining him what all we did in the party, how much fun we had but noticed that hardly he was listening. Asked him “Are you alright?” to which he replied murmuring “haan thik hun” (I am alright). I turned on the music and continued with the party mood. Suddenly there was a flash of light, all things went blank, no sound, and no music.

A morning in Bangalore, I am lying on bed, looking outside the window. I see a beautiful tree with purple flowers and sun shining brightly. No one is shouting, there is silence all around I closed my eyes, tears falling down my cheeks. 

Thursday, July 18, 2013

Why use sql server express?

Many times I have found people asking questions like “why to use sql express?”
Today we will discuss about some points why to use sql express.

·         First of all SQl express is free product of Microsoft
·         When it is not required to use all features of sql server we can use sql express
·         Sql express supports maximum size of 4GB (sql server 2008 and earlier) and 10 GB (sql server 2008R2) per database excluding the log files
·         The tool should be used for small to medium scale applications
·         This edition supports many of the more advanced features available in the full SQL Server version, such as stored procedures, views, functions, CLR integration, snapshot isolation, and XML support
·         There is no problem for concurrent users to access and update data at the same time

Hardware-utilization limits:

  • Single physical CPU, but multiple cores allowable
  • 1 GB of RAM (runs on a system with any RAM amount, but uses only at most 1 GB)

Merge statement sql server 2008

Merge statement sql


Merge statement is used to insert and update existing conditions data based on conditions whether they are met or not.
Facts about Merge statement:
  • We can perform atomic statements (Insert,delete,update) based on conditions
  • End of merge statement contains semicolon mark (;)
  • Merger is defined by ANSI SQL, works in other database platforms as well
  • Contains conditions as MATCHED and NOT MATCHED

CREATE TABLE STUDENT (
Student_Id int,
First_Name  VARCHAR(20),
Last_Name   VARCHAR(20),
Branch_No     int,
Fees      int);

INSERT INTO STUDENT VALUES (1, 'Neil', 'Sarkar', 11, 100000);
INSERT INTO STUDENT VALUES (2, 'deepak', 'Mishra', 52, 100000);
INSERT INTO STUDENT VALUES (3, 'Neha', 'Kumari', 52, 50000);
INSERT INTO STUDENT VALUES (4, 'Deepa', 'Sarkar', 52, 40000);
INSERT INTO STUDENT VALUES (5, 'Mukul', 'Bharti', 52, 30000);
INSERT INTO STUDENT VALUES (6, 'Vipul', 'Dalvi', 52, 70000);
INSERT INTO STUDENT VALUES (7, 'Michael', 'Puling', 52, 90000);


CREATE TABLE SCHOLARSHIP (
Student_Id int, Scholarship int DEFAULT 200);

INSERT INTO SCHOLARSHIP (Student_Id) VALUES (1);
INSERT INTO SCHOLARSHIP (Student_Id) VALUES (2);
INSERT INTO SCHOLARSHIP (Student_Id) VALUES (4);
INSERT INTO SCHOLARSHIP (Student_Id) VALUES (6);
INSERT INTO SCHOLARSHIP (Student_Id) VALUES (7);


MERGE [SCHOLARSHIP] AS S
USING
(
  SELECT Student_Id, Fees
  FROM STUDENT
  WHERE Branch_No =52) as E
ON (S.Student_Id = E.Student_Id)
WHEN MATCHED THEN
  UPDATE SET S.Scholarship = E.Fees * 10
WHEN NOT MATCHED THEN
  INSERT (Student_Id, Scholarship)
  VALUES (E.Student_Id, E.Fees * 0.6);

Tuesday, July 16, 2013

SSIS- script task to export data from database table to .csv file

SSIS- script task to export data from database table to .csv file

User::INPUT_FILE_PATH - input file path to get output file name same as the input file name

User::OutputPath - output path where we get the output in .csv format

User::outputdatabaseConnectionString - Database connection string




/*
   Microsoft SQL Server Integration Services Script Task
   Write scripts using Microsoft Visual C# 2008.
   The ScriptMain is the entry point class of the script.
*/

using System;
using System.Data;
using Microsoft.SqlServer.Dts.Runtime;
using System.Windows.Forms;
using System.Web;
using System.Collections.Generic;

//using System.Linq;
//using System.Web.Security;
//using System.Web.UI;
//using System.Web.UI.WebControls;
//using System.Web.UI.Adapters;
//using System.Web.UI.WebControls.WebParts;
//using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
using System.Text;
using System.IO;


namespace ST_f9e64226a54d4da28a70f42ab090a637.csproj
{
    [System.AddIn.AddIn("ScriptMain", Version = "1.0", Publisher = "", Description = "")]
    public partial class ScriptMain : Microsoft.SqlServer.Dts.Tasks.ScriptTask.VSTARTScriptObjectModelBase
    {
        string _FileName = "";
        string unicode = "utf-8";
        #region VSTA generated code
        enum ScriptResults
        {
            Success = Microsoft.SqlServer.Dts.Runtime.DTSExecResult.Success,
            Failure = Microsoft.SqlServer.Dts.Runtime.DTSExecResult.Failure
        };
        #endregion

       
        public void Main()
        {
            // TODO: Add your code here
            string path = Dts.Variables["User::INPUT_FILE_PATH"].Value.ToString();
            String fname = Dts.Variables["User::OutputPath"].Value.ToString() + "\\" + GetFileNames(path);
            Dts.TaskResult = (int)ScriptResults.Success;
            //GetFileNames(path);
            CreateCSVFile(GetTableData(), fname);
        }
        //public static Encoding GetEncoding(string unicode);

        public string GetFileNames(string path)
        {

            string tFileName = new DirectoryInfo(path).GetFiles("*.csv")[0].Name;

            //string[] files = Directory.GetFiles(path);
            //string tfileName=files[0].ToString(); //as assuming always one file
            string[] fileparts = tFileName.Split('_');
            string filePart = fileparts[0] + "_" + fileparts[1] + "_" + fileparts[2] + "_" + "Othertext" + "_" + fileparts[5];


            _FileName = filePart;
            return _FileName;
        }


        public DataTable GetTableData()
        {

            String connstring = Dts.Variables["User::outputdatabaseConnectionString"].Value.ToString();
           
            SqlConnection conn = new SqlConnection(connstring);

            SqlCommand cmd = new SqlCommand("select * from table", conn);
            cmd.CommandType = CommandType.Text;
            SqlDataAdapter adap = new SqlDataAdapter(cmd);
            DataTable dt = new DataTable();
            adap.Fill(dt);
            return dt;
        }


        public void CreateCSVFile(DataTable dt, string strFilePath)
        {
            StreamWriter sw = new StreamWriter(strFilePath, false);
            int iColCount = dt.Columns.Count;
            for (int i = 0; i < iColCount; i++)
            {
                sw.Write(dt.Columns[i]);
                if (i < iColCount - 1)
                {
                    sw.Write(",");
                }
            }
            sw.Write(sw.NewLine);
            // Now write all the rows.
            foreach (DataRow dr in dt.Rows)
            {
                for (int i = 0; i < iColCount; i++)
                {
                    if (!Convert.IsDBNull(dr[i]))
                    {
                        sw.Write(dr[i].ToString());
                    }
                    if (i < iColCount - 1)
                    {
                        sw.Write(",");
                    }
                }
                sw.Write(sw.NewLine);
            }
            sw.Close();
        }

    }

}



Friday, July 5, 2013

Excel Functions - Statistical Functions part2



Excel Functions - Statistical functions part 1



Excel Functions - Logical Functions



Excel Functions - Lookup







Excel Functions - TEXT functions





Excel Functions - Conditional Formatting




Excel Function - Date and Time












The Next Topic Conditional Formatting will be explained in next blog

Wednesday, July 3, 2013

dynamic pivot table

Dynamic pivot table:- Easy learning

create table TestData
(
    Sno int,
    product varchar(30),
    product_value varchar(50)
   
)

--select * from TestData

INSERT [dbo].[TestData] ([Sno], [product], [product_value]) VALUES (1, N'A', N'100')
INSERT [dbo].[TestData] ([Sno], [product], [product_value]) VALUES (2, N'A', N'200')
INSERT [dbo].[TestData] ([Sno], [product], [product_value]) VALUES (3, N'A', N'300')
INSERT [dbo].[TestData] ([Sno], [product], [product_value]) VALUES (4, N'B', N'400')
INSERT [dbo].[TestData] ([Sno], [product], [product_value]) VALUES (5, N'A', N'500')
INSERT [dbo].[TestData] ([Sno], [product], [product_value]) VALUES (6, N'C', N'600')
INSERT [dbo].[TestData] ([Sno], [product], [product_value]) VALUES (7, N'C', N'700')
INSERT [dbo].[TestData] ([Sno], [product], [product_value]) VALUES (8, N'B', N'800')



DECLARE @cols AS VARCHAR(MAX),
            @colsname as varchar(max),
            @query  AS VARCHAR(MAX);
           
set @cols = ''
set @colsname = ''

SELECT @colsname = COALESCE(@colsname + '['+ product+'],' ,','),
            @cols = COALESCE(@cols + 'ISNULL(sum(CAST(['+ product+']AS FLOAT)),0)'+ '['+ product+'],' ,',')
FROM
(
select distinct product from TestData    
)
TEMP

SET @colsname = SUBSTRING(@colsname,1,LEN(@colsname) -1)
SET @cols = SUBSTRING(@cols,1,LEN(@cols) -1)

set @query = 'SELECT Sno, ' + @cols + 'from
            (
                select Sno, product_value,product
                from TestData
            ) x
            pivot
            (
                max(product_value)
                for product IN(' + @colsname + ')
            ) p group by sno'


execute(@query)