Pages

Friday, May 30, 2014

SSIS - Split a file into multiple files based on string pattern

Scenario:

I have a sample file which looks like this 



Test.his




I have a scenario, where in I need to split the above file into multiple files at every occurrence of the word "Group". 

It means, I need to split the above "Test.his" file  into 7 files (Why is it 7 ? Answer: Count the occurrences of the word "Group").

Solution: 

The solution for this gets simpler using an Execute SQL Task , Control Table in the database , For Each Loop Container and Script Task functionality. Lets see how we could achieve this. 

Step 1: 

Lets create a control table in our database. 



CREATE TABLE [dbo].[Test_ControlTable](

[GROUPNAME] [varchar](20) NULL,

[SEARCHINDEX] [varchar](50) NULL


GO


Step 2: 

Execute the below mentioned script to insert rows into the table. 

INSERT INTO [dbo].[Test_ControlTable] VALUES('PATIENT','Group:PATIENT');
GO
INSERT INTO [dbo].[Test_ControlTable] VALUES('APRENURS','Group:APRENURS');
GO
INSERT INTO [dbo].[Test_ControlTable] VALUES('PHYS','Group:PHYS');
GO
INSERT INTO [dbo].[Test_ControlTable] VALUES('PR','Group:PR');
GO
INSERT INTO [dbo].[Test_ControlTable] VALUES('PN','Group:PN');
GO
INSERT INTO [dbo].[Test_ControlTable] VALUES('PROCTIM','Group:PROCTIM');
GO
INSERT INTO [dbo].[Test_ControlTable] VALUES('STUDY','Group:STUDY');
GO

Your SELECT * from [dbo].[Test_ControlTable] gives the below results.




Step 3: 

Create a new project in Visual Studio(BIDS) with Project Name as Test.



Step 4:

Drag and drop Execute SQL Task into work space of the package.



And configure it as below

ResultSet            :  Full Result Set
 SQLStatement  :  SELECT GroupName, SearchIndex FROM [dbo].[Test_ControlTable]



In the Result set tab, 

Click on Add, and give Result name as 0 (Zero) and map it to Object Variable (create one in variables  window as shown in the image )




Step 5:

Drag and drop For Each Loop container and Script Task into the work space as shown below.


This means, the script task runs for every row that is coming from the control table.

Step 6: 

Create two variables in the variables window as shown below. 

                                        

Step 7: 

Configure the For Each Loop container as shown




Step 8: 

Edit the Script Task with the following script:


#region Namespaces
using System;
using System.Text;
using System.Linq;
using System.IO;
using System.Data;
using Microsoft.SqlServer.Dts.Runtime;
using System.Windows.Forms;
using System.Collections.Generic;
using System.Text.RegularExpressions;
#endregion


public void Main()
{
// TODO: Add your code here

            //Declare and Initialize the variables 
            String vFileName = "C:\\Users\\tmhsxk35\\Documents\\Test.his" ;
            String vGroupName = Dts.Variables["User::vGroupName"].Value.ToString();
            String vSearchIndex = Dts.Variables["User::vSearchIndex"].Value.ToString();
            String vSplitFilePath = "C:\\Users\\tmhsxk35\\Documents\\SplitFiles\\";


            // Reading the file 
            String s = File.ReadAllText(vFileName, Encoding.Default);

            //Finding the location of vSearchIndex 
            Match match = Regex.Match(s, @"\b" + Regex.Escape(vSearchIndex) + @"\b",                           RegexOptions.IgnoreCase);

            //If the search is successful, then capture the position of the Index into vPos
            if (match.Success)
            {
                int vPos = match.Index;

                //Assigning the position of next occurence of "Group" to vNextPos
                int vNextPos = s.IndexOf("Group", vPos + 1);

                //Capturing the content between the occurences of "Group" into vContent
                String vContent = s.Substring(vPos, vNextPos - vPos - 2);

                //Writing the content to a file
                StreamWriter sw = File.CreateText(vSplitFilePath + vGroupName + ".csv");
                sw.Write(vContent);
                sw.Flush();
                sw.Close();

                Dts.TaskResult = (int)ScriptResults.Success;
            }  


Dts.TaskResult = (int)ScriptResults.Success;
}






Use the script mentioned above to split the files. 

Save the package. And execute the package to see the file split to 7 files at the path mentioned above. 






Please modify the script as required.

Thanks for taking time to check out the post!

P.S:

 I used For Each Loop Container, Control Table, Execute SQL Task because my searchIndex is a variable. If your searchIndex is constant, you dont have to use them. Just initialize everything in variables inside the script task. 

Friday, May 23, 2014

Mickey Mouse Themed Gift Wrap

We were planning to have a perfect Mickey Mouse party for our LO.  Here is the outcome for wrapping the gifts.





Initially, we found it very difficult to wrap a circular gift with the normal set of gift wraps we had, then we bought another set of black and red craft paper gift wrap from Micheal's. The idea of changing the wrapping sheets, was so fruitful. 

For the ears, I cut the black felt out and glued it to the gift with the Hot glue gun. 

Credits to my husband for the last minute idea!



Tuesday, March 11, 2014

T-SQL - To convert any format phone number into Standard US format

CREATE FUNCTION [dbo].[fnStandardPhone]
   (
     @PhoneNumber VARCHAR(32)
   )
RETURNS VARCHAR(32)
AS 
   BEGIN

       DECLARE @Phone CHAR(32)

   

       SET @Phone = @PhoneNumber

   

   -- cleanse phone number string


   WHILE PATINDEX('%[^0-9]%', @PhoneNumber) > 0 
           SET @PhoneNumber = REPLACE(@PhoneNumber,
                                      SUBSTRING(@PhoneNumber,
                                                PATINDEX('%[^0-9]%',
                                                         @PhoneNumber), 1),
                                      '')

   

   -- skip foreign phones

       IF ( SUBSTRING(@PhoneNumber, 1, 1) = '1'
            OR SUBSTRING(@PhoneNumber, 1, 1) = '+'
            OR SUBSTRING(@PhoneNumber, 1, 1) = '0'
          )
           AND LEN(@PhoneNumber) > 11 
           RETURN @Phone


     -- build US standard phone number

       SET @Phone = @PhoneNumber

   

       SET @PhoneNumber = SUBSTRING(@PhoneNumber, 1, 3) + '-'
           + +SUBSTRING(@PhoneNumber, 4, 3) + '-' + SUBSTRING(@PhoneNumber, 7,
                                                             4)

   

       IF LEN(@Phone) - 10 > 1 
           SET @PhoneNumber = @PhoneNumber + ' x' + SUBSTRING(@Phone, 11,
                                                             LEN(@Phone) - 10)

   

       RETURN @PhoneNumber

   END


GO

Tuesday, March 4, 2014

TSQL - To visually identify if there is a Carriage Return / New Line character within the VARCHAR column

Scenario:

We have a scenario, where in we need to know if there is any carriage return('\r') or a new line('\n') character is embedded in a VARCHAR/TEXT column. 


Solution: 

This cannot be simply achieved by using SELECT statement. PRINT function enables us to know the presence of such characters. Let us now see how.

Step 1:

 Let me a create simple table for your easy understanding using the following script. 

CREATE TABLE [dbo].[TestDB_Test1](
[COL1] [int] IDENTITY(1,1) NOT NULL,
[COL2] [varchar](150) NULL
) ON [PRIMARY]

GO


Step 2: 

Lets insert two rows for COL2, one  without carriage return/new line  and the other one with the carriage return/new line. 

-- Sample data without carriage return/ new line character

INSERT INTO [dbo].[TestDB_Test1]
           ([COL2])
     VALUES
           ('I am Line1. I am Line2')
GO



-- Sample data with carriage return/new line character

INSERT INTO [dbo].[TestDB_Test1]
            ([COL2])
VALUES
('I am Line1.' + CHAR(10)+ 'I am Line2')

Step 3: 

Run a SELECT query, to see how the data appears. 


SELECT * from dbo.TESTDB_Test1 





The two rows appears to be same after a SELECT query. 

Step 4: 

Create a variable to hold the value of COL2 using a select query. 

DECLARE @var varchar(150) 

SELECT @var = col2 FROM TestDB_Test1 where col1 = 1

PRINT @var





DECLARE @var varchar(150) 

SELECT @var = col2 FROM TestDB_Test1 where col1 = 2

PRINT @var



This clearly shows that the text in row 2 had a new line character in between.  In order to remove such redundant characters, one could always use REPLACE function. 

Wednesday, February 19, 2014

Mickey Mouse Themed Guest Message

A cute way to treasure the message from the guest to the LO on the 1st Birthday. 


Mickey Mouse Oreo Cookies

This item was also part of my LO's first birthday party. The little guests in the party thoroughly enjoyed eating them and loved the taste too.  


Ingredients

Oreo cookies - Regular size - 1 pack

Mini Oreo cookies - 1 pack

Wax paper

Red Chocolate Melts - 1 pack (we got it from Jo-Ann)

Dark Chocolate Melts - 1 pack(Also from Jo-Ann)

White circular sprinklers / White tube (From Michael's)

Procedure

Melt the Chocolate(Red and Dark Chocolate)

  • For the melts, pour some of red chocolate melts into a bowl/cup, put them in the microwave for about 30 seconds. 
  • Mix the melts frequently. 
  • Once the consistency of the chocolate is attained, leave it aside. 
Caution: Do not over heat the chocolate melts, because if you overheat, they may end up becoming powder. 

  •   Repeat the same procedure for Dark chocolate melts as well. 

Make the cookies

  • Dip the regular sized Oreo cookie into chocolate melt until half way. 
  • Place it on a wax sheet spread over a tray, undisturbed. 
  • Repeat this procedure for all the regular sized Oreo cookies that you want. 
  • Put the tray in the refrigerator for few minutes(3 - 5 minutes approx. ), to let the chocolate dry. 
  • Remove the cookies from the refrigerator and mark lines over the top of the cookie to place the mini Oreo cookies over it(resembling ears of the cookie)
  • Dip a small edge of the mini Oreo into the Dark chocolate melt, and place it over the regular one, touching its surface like the one in the picture. 
  • Repeat for the other end too. 
  • Now, repeat the same procedure for the rest of the cookies. 
  • Place them in the refrigerator for it to solidify for about 3- 5 minutes. 
  • Remove the cookies from the refrigerator and place two white circular sprinkles/ white gelatin to represent the buttons over the red melt. 

Picture speaks more than words.... 


Tuesday, February 18, 2014

Mickey Themed First Birthday Photo Gallery

We have made this photo gallery for our LO's first birthday. It looked so cute,  everyone loved to see the pictures and it matched our theme as well. You can make it in your party as well. 

All you need is, 


Black craft sheets - 13 (qty) (we got it from Michael's)

Glue

Yellow/ Red Satin ribbon - 1

Carving Knife / Carving Pen

Pictures of your LO (From NB to 12 month old) - 13 


Steps: 


  • Draw two concentric circles of diameters 4 and 5 cm approx. on the black craft paper that    you have.  
  •  Draw two circles  of 0.5 - 1 cm diameter on top of the outer circle, to represent mickey      ears. 
  • Carve out the inner circle, to see through it using a carving knife/pen.
  • Glue the picture to the back of the outer circle and carve out the excess part of the picture to make it a circular one. 
  • Punch a hole on each of the ear to let the satin ribbon pass through it.
  •  Connect each mickey photo through this ribbon to get your mickey gallery.