WTF is an Enum?

June 4th, 2009 NothingMan No comments

I’m a data-person but I like to change it up every now and then jump into some real code.  I was dabbling in C# last week and was looking into Enums.  I had heard about them a lot but never REALLY knew what they were or how they were constructed, so I forced myself to figure out WTF they were.

 

In computer programming, an enumerated type (also called enumeration or enum) is a data type consisting of a set of named values called elements, members or enumerators of the type. The enumerator names are usually identifiers that behave as constants in the language. A variable that has been declared as having an enumerated type can be assigned any of the enumerators as a value.

For example, the four suits in a deck of playing cards may be four enumerators named CLUB, DIAMOND, HEART, SPADE, belonging to an enumerated type named suits. If a variable V is declared having suits as its data type, one can assign any of those four values to it.

The enumerators are necessarily distinct, even though some languages may allow the same enumerator to be listed twice in the type’s declaration. The enumerators need not be complete or compatible in any sense. For example, an enumerated type called color may be defined to consist of the enumerators RED, GREEN, ZEBRA, and MISSING. In some languages, the declaration of an enumerated type also defines an ordering of its members.

Some enumerator types may be built into the language. The Boolean type, for example is often a pre-defined enumeration of the values FALSE and TRUE. Many languages allow the user to define new enumerated types.

 

Here’s a quick look at how to create an Enum and how to use them.

using System;

// declares the enum
public enum Volume
{
   Low,
   Medium,
   High
}

// demonstrates how to use the enum

class
EnumSwitch
{
   static void Main()
   {
      // create and initialize 
      // instance of enum type

      Volume myVolume = Volume.Medium;

      // make decision based
      // on enum value
      switch (myVolume)
      {
         case Volume.Low:
            Console.WriteLine("The volume has been turned Down.");
            break;
         case Volume.Medium:
            Console.WriteLine("The volume is in the middle.");
            break;
         case Volume.High:
            Console.WriteLine("The volume has been turned up.");
            break;
      }
      Console.ReadLine();
   }
}

VN:F [1.9.6_1107]

Rating: 0.0/5 (0 votes cast)
VN:F [1.9.6_1107]
Rating: 0 (from 0 votes)
Categories: Code, g33k Tags: , , ,

Escape Syntax in T-SQL LIKE Statement with ‘_’

May 27th, 2009 NothingMan No comments

In a like statement, “%” is a wildcard for everything after or before it and “_” is a wildcard for one character.  Observe:

LIKE ‘%Z’ would return ANYthing that ended with Z.

 

LIKE ‘%Z%’ would return ANYthing with a Z in it.

 

LIKE ‘Z__’ would return anything that started with Z and had at least 2 characters after it, like:

ZOO, ZXY, ZAP

but would not return:

ZA, ZO, Z, or XYZ

 

LIKE ‘Z%’ would return anything that STARTED with Z.

 

LIKE ‘_Z%’ would return anything that had one character, then a Z, then anything or nothing else like:

YZX, YZ, ZZZ

but would not return:

XYZ, ABCZ

 

However, if you want to look for the literal value of ‘%’ or ‘_’, you need to escape it.  For instance, if you want to look for anything that begins with ‘Z_’, then you would need to escape the ‘_’, otherwise, you would be looking for anything that started with ‘Z’ followed by one wildcard character ‘_’, followed by a wildcard of any number of characters ‘%’, returning anything that just started with ‘Z’ and had at lease one character after it.

select table_catalog, column_name, table_schema, table_name
from information_schema.columns
where column_name like 'Z\_%' escape '\'

This would only return data that started with 'Z_'.

VN:F [1.9.6_1107]

Rating: 0.0/5 (0 votes cast)
VN:F [1.9.6_1107]
Rating: 0 (from 0 votes)
Categories: BI, Code, Tips Tags: , , , ,

Generate ROWNUM pseudo-column in SSIS

May 27th, 2009 NothingMan No comments

I posted earlier on how to generate a rownumber in SQL 2000, but that would not work as a source query in SSIS for some reason.  Without having to create a stored procedure or temp tables based on other temp tables, I wanted a simple way to generate this rownum in SSIS.  I was considering something with variable expressions, but then I found a way to do it with a Script Component.

Drag a Script Component Task into your DataFlow and connect it between your source and destination tasks.  Open it up and click “Inputs and Outputs”.  Double Click “Output 0″ and highlight “Output Columns” and click Add Column.  For this code to work, name that new column “rownum“.

Then open the script tab and click “Design Script” and paste this code over what is already there:

  

Imports System

Imports System.Data

Imports System.Math

Imports Microsoft.SqlServer.Dts.Pipeline.Wrapper

Imports Microsoft.SqlServer.Dts.Runtime.Wrapper

 

Public Class ScriptMain

    Inherits UserComponent

    Dim counter As Integer = 0

 

    Public Overrides Sub Input0_ProcessInputRow(ByVal Row As Input0Buffer)

 

        Row.rownum= counter

        counter = counter + 1

    End Sub 

End Class

 

VN:F [1.9.6_1107]

Rating: 5.0/5 (1 vote cast)
VN:F [1.9.6_1107]
Rating: 0 (from 0 votes)
Categories: BI, Code, Tips Tags: , , ,

T-SQL Delete Join

May 22nd, 2009 NothingMan 1 comment

Here’s are two quick ways to Delete data in one table based on another table.  This works perfectly in an ETL job where you have a staging table that indicate whether to Insert, Update, or Delete the data in the other table.

The first one uses an inner join, the second uses a simple EXISTS clause.

DELETE b

  FROM [dbo].[TABLE_1] b

 INNER JOIN [dbo].[TABLE_2] w

    ON b.[ROW_ID] = w.[ROW_ID]

 WHERE w.[CTRL_CD] = 'D'

 

 

DELETE b

  FROM [dbo].[TABLE_1] b

 WHERE EXISTS (

            SELECT 1

          FROM [dbo].[TABLE_2] w

         WHERE b.[ROW_ID] = w.[ROW_ID]

           AND w.[CTRL_CD] = 'D')

 

VN:F [1.9.6_1107]

Rating: 4.8/5 (5 votes cast)
VN:F [1.9.6_1107]
Rating: +1 (from 1 vote)
Categories: BI, Code, Tips Tags: , , ,

Google Geocoding in SSIS

May 20th, 2009 NothingMan 4 comments

I have an old YouTube tutorial on how to use Google Geocoding within SSIS, but I lost all the downloadable scripts.  I recently had a few people asking me if I could send them the scripts, so I deiceded to rewrite them.

Again, you can check out the YouTub video (it’s rough) for more details, just go to http://www.youtube.com/watch?v=HTSHzR-wSgc with this DISCLAIMER:  This code was just thrown together and is quite ugly and my microphone was terrible, I usually sound much better than that Google Geocoding in SSIS  :-)

In a nutshell, I sniped about 18,000 golfcourses off the web with a PHP script and got basic course information for all of them, including the address information.  I wanted to use Google Maps to display these courses, so I thought I’d use Google Geocoding.  Caution, they don’t like it when you hit them 1000 times per second, so I would recommend using a Sleep command in your code like I did so you can throttle it without getting kicked off. 

So, I have an OLE Source task that reads from my database.  I created a Derived Column task to create placeholders for latitude, longitude, and level of accuracy.  I created a Script Component and selected street, city, state, and zip as input columns and added lat, long, and accuracy as read/write columns. 

Open the script editor, add a reference to System.Web, then create a new class called Google GeoCode, or whatever the heck you want to call it and paste in this code:

Option Strict Off

''' Might need this, might not

Imports System

Imports System.Data

Imports System.Math

Imports System.Net

Imports System.Web

Imports System.IO

Namespace GoogleGeoCoder

    Public Interface ISpatialCoordinate

        Property latitude() As Double

        Property longitude() As Double

    End Interface

    ''' <summary>   

    ''' Coordiate structure. Holds Latitude and Longitude.   

    ''' </summary>   

    Public Structure Coordinate

        Implements ISpatialCoordinate

 

        Private _latitude As Double

        Private _longitude As Double

 

        Public Sub New(ByVal lattitude As Double, ByVal longitude As Double)

            _latitude = lattitude

            _longitude = longitude

        End Sub

 

        Public Property latitude() As Double Implements ISpatialCoordinate.latitude

            Get

                Return _latitude

            End Get

            Set(ByVal value As Double)

                _latitude = value

            End Set

        End Property

 

        Public Property longitude() As Double Implements ISpatialCoordinate.longitude

            Get

                Return _longitude

            End Get

            Set(ByVal value As Double)

                _longitude = value

            End Set

        End Property

 

    End Structure

    Public Class GeoCode

        Const _googleUri As String = "http://maps.google.com/maps/geo?q="

        Const _googleKey As String = "yourgooglekeyhere"  ' get your own       

        Const _outputType As String = "csv"

        Private Shared Function GetGeoCodeUri(ByVal address As String) As Uri

            address = HttpUtility.UrlEncode(address)

            Return New Uri(String.Format("{0}{1}&output={2}&key={3}", _googleUri, address, _outputType, _googleKey))

        End Function

        ''' <summary>       

        ''' Gets a Coordinate from a address.       

        ''' </summary>       

        ''' <param name="address">An address.       

        ''' <remarks>       

        ''' <example>1600 Amphitheatre Parkway Mountain View, CA 94043</example>       

        ''' </remarks>       

        ''' </param>       

        ''' <returns>A spatial coordinate that contains the latitude and longitude of the address.</returns>       

        Public Shared Function GetCoordinates(ByVal address As String) As Coordinate

            Dim client As WebClient = New WebClient()

            Dim uri As Uri = GetGeoCodeUri(address)

            Dim geoCodeInfo As String()

            'The first number is the status code,            

            'the second is the accuracy,            

            'the third is the latitude,            

            'the fourth one is the longitude.           

            Try

                geoCodeInfo = client.DownloadString(uri).Split(",")

                Return New Coordinate(Convert.ToDouble(geoCodeInfo(2)), Convert.ToDouble(geoCodeInfo(3)))

            Catch ex As Exception

                Return New Coordinate(0.0, 0.0)

            End Try

        End Function

    End Class

End Namespace

 

Save it and then go back to the main script and add Import that class (see code).  Notice, the way I’m getting the level of accuracy with my ugly nested IF statements isn’t the prettiest way to do this, use your imagination.  Copy in this code into the Main Script:

 

' Microsoft SQL Server Integration Services user script component

' This is your new script component in Microsoft Visual Basic .NET

' ScriptMain is the entrypoint class for script components

 

Imports System

Imports System.Data

Imports System.Math

Imports Microsoft.SqlServer.Dts.Pipeline.Wrapper

Imports Microsoft.SqlServer.Dts.Runtime.Wrapper

Imports ScriptComponent_4a8732cababc49a999159a91c737082a.GoogleGeoCoder

 

Public Class ScriptMain

    Inherits UserComponent

 

    Public Overrides Sub Input0_ProcessInputRow(ByVal Row As Input0Buffer)

 

        Dim coordinate As Coordinate = GeoCode.GetCoordinates(Row.street & ", " & Row.city & ", " & Row.state & ", " & Row.zip)

 

        If ((coordinate.latitude <> 0) And (coordinate.longitude <> 0)) Then

            Row.lat = Convert.ToDecimal(coordinate.latitude)

            Row.long = Convert.ToDecimal(coordinate.longitude)

            Row.acc = 1

        Else

            coordinate = GeoCode.GetCoordinates(Row.city & ", " & Row.state & ", " & Row.zip)

            If ((coordinate.latitude <> 0) And (coordinate.longitude <> 0)) Then

                Row.lat = Convert.ToDecimal(coordinate.latitude)

                Row.long = Convert.ToDecimal(coordinate.longitude)

                Row.acc = 2

            Else

                coordinate = GeoCode.GetCoordinates(Row.zip)

                If ((coordinate.latitude <> 0) And (coordinate.longitude <> 0)) Then

                    Row.lat = Convert.ToDecimal(coordinate.latitude)

                    Row.long = Convert.ToDecimal(coordinate.longitude)

                    Row.acc = 3

                Else

                    coordinate = GeoCode.GetCoordinates(Row.city & ", " & Row.state)

                    If ((coordinate.latitude <> 0) And (coordinate.longitude <> 0)) Then

                        Row.lat = Convert.ToDecimal(coordinate.latitude)

                        Row.long = Convert.ToDecimal(coordinate.longitude)

                        Row.acc = 4

                    Else

                        coordinate = GeoCode.GetCoordinates(Row.state)

                        If ((coordinate.latitude <> 0) And (coordinate.longitude <> 0)) Then

                            Row.lat = Convert.ToDecimal(coordinate.latitude)

                            Row.long = Convert.ToDecimal(coordinate.longitude)

                            Row.acc = 5

                        End If

                    End If

                End If

            End If

        End If

    End Sub

 

End Class

 

VN:F [1.9.6_1107]

Rating: 5.0/5 (3 votes cast)
VN:F [1.9.6_1107]
Rating: 0 (from 0 votes)
Categories: BI, Code, Misc, g33k Tags: , ,

RowNum() Equivalent in SQL 2000+

May 18th, 2009 NothingMan No comments

Oracle has a pseudo-column called ROWNUM that allows you to display the row number for each row.  There are infinite reasons why you might want to use the ROWNUM, but in SQL it’s not nearly as easy to determine.

 

In Oracle, it’s simply

SELECT ROWNUM from table_name

 

In SQL 2005+, there is actually a ROW_NUMBER() function, but you have to give it some more information to use it.

ROW_NUMBER ( )     OVER ( [ <partition_by_clause> ] <order_by_clause> )

 

For example:
use [Database]
select row_number() over (order by data_srce_id desc) rownum

      ,data_srce_id
from data_srce 

 

rownum

data_srce_id

1

8

2

7

3

6

4

5

5

4

6

3

7

2

8

1

9

-1



 

However, in SQL 2000 it’s a little more difficult.  The only way I’ve found is using the IDENTITY() function, which requires an INTO statement, so you pretty much have to load the results into a #temporary table and then select from the #temporary table like this:

use [Database]

SELECT IDENTITY(int, 1,1) id

      ,t1.[column1]           col1

      ,t1.[column2]           col2

      ,t1.[column3]           col3

      ,t2.[column2]           col4

  INTO #Temp

  FROM [dbo].[Table] t1

 INNER JOIN [dbo].[Table2] t2

    ON t.[column] = t2.[column]

 

select *

  from #Temp

VN:F [1.9.6_1107]

Rating: 0.0/5 (0 votes cast)
VN:F [1.9.6_1107]
Rating: 0 (from 0 votes)
Categories: BI, Code, Tips Tags: , , , ,

WordPress SEO – Great Tips

May 17th, 2009 Rick No comments
Categories: Misc, Site, Social, Tips Tags: , ,

Sending Mail with MSSQL

May 15th, 2009 NothingMan 4 comments

Here’s a quick and dirty way to send email via MSSQL.  For some reason, we’re not allowed to send email using the Email Task in SSIS, so I chose this option.  Unfortunately, even if you have access to execute sp_SQLSMTPMail, you might not have access to run xp_cmdshell.

 

I ended up having to create my SSIS package with a SQL Task that runs this proc, then I had to run it with a SQL Agent Job with a proxy account that had access to xp_cmdshell.  Fun stuff.

 

 

 

 

declare @developerperson varchar(80)

declare @message_body varchar(1000)

 

set @message_body =

‘Dear ‘ + @developerperson + ‘Use \n for line breaks and escape your ”s’

 

 

EXECUTE dbo.sp_SQLSMTPMail

      @vcTo = ‘You@you.com’,

      @vcCC= ‘Them@them.com’,

      @vcSubject = ‘Super Cool SQL Email’,

      @vcBody = @message_body,

      @vcFrom = ‘Me@me.com’,

      @vcSMTPServer = ‘SMTPName’,

      @vcSenderName = ‘Some One’,

      @vcServerName = @@SERVERNAME –no need to specify because this is the default anyway

Or, lets say you want to email query results as an attachment:

EXECUTE dbo.sp_SQLSMTPMail

  @vcTo=‘you@you.com’

, @vcCC=‘them@them.com’

, @vcSubject=‘Here is your wonderful report that is terribly formatted as a txt file attachment’

, @vcquery= ‘select col1, col2, col3, col4 from database.schema.table’

 

 

 

 

 

 

 

 

Here’s the actual Proc definition: Read more…

VN:F [1.9.6_1107]

Rating: 0.0/5 (0 votes cast)
VN:F [1.9.6_1107]
Rating: 0 (from 0 votes)
Categories: BI, Code, Tips Tags: , , , , , , ,

Delete TOP n Records in T-SQL

May 13th, 2009 NothingMan No comments

If you’re trying to delete the first n records in a table, here’s how to do it in SQL 2005: Read more…

VN:F [1.9.6_1107]

Rating: 5.0/5 (1 vote cast)
VN:F [1.9.6_1107]
Rating: 0 (from 0 votes)
Categories: BI, Code, Tips Tags: , ,

What recruiters look for in a LinkedIn profile: 8 tips

May 11th, 2009 NothingMan No comments

This was a great article on LinkedIn that I thought I would share.  I’ve done most of this and I’m ALWAYS getting LinkedIn messages for job openings.  It’s a very valuable resource in this economy!

 1. Make your LinkedIn profile 100% complete

•    Include all companies, education, and awards. These are the key items on which we recruiters search.
•    References are very important. The more we know about you the better.
•    The more robust your profile, the higher you will be in the Google search rankings.
•    The more information a recruiter has upfront, the more efficient the search process.
•    Update your LinkedIn profile here

2. Use a profile picture that you use on multiple sites

•    A picture helps to create and reinforce your online brand
•    It will help a recruiter identify you on the interview day at “Starbucks”
•    Add a profile picture here

3.  Use the “Specialties” box to fill in keywords

•    List as many keywords as possible that are relevant to your roles, capabilities, and interests that will help you turn up on LinkedIn Search
•    Update your profile summary and specialties here

4. Update your LinkedIn “Status” regularly

•    Link to articles you have written or in which you are quoted
•    Update status with your latest blog posts
•    Discuss business accomplishments
•    If you are actively looking for a job, tell people what you are looking for!
•    Update your status on other social networking sites such as Twitter. Try services like ping.fm that allow you to update your status across multiple sites.

5. Make changes to your profile after every job change or promotion

•    The recruiters you are linked to will notice these changes
•    It is harder to be found if people don’t know where you are
•    Update your LinkedIn profile as you would your change-of-address at the post office

6. Include your web site and blog links

•    Add suitable weblinks to the “Websites” section on your LinkedIn profile
•    This could range from your career blog to your Twitter profile. Alternatively, you can also link to a guest blog post you wrote recently.
•    Update your “Websites” section here

7.  Do not block incoming emails

•    No matter how popular you think you are, you will not be overwhelmed. I promise!
•    The LinkedIn community is all about participation so feel free to accept incoming communication from fellow LinkedIn users. Update your contact settings here.
•    If a recruiter reaches out to you and you are not interested, let him or her know or better yet refer a friend
•    LinkedIn actually allows you to control how you receive emails and notifications. Update your settings here.

8. Increase your number of trusted connections!

•    Use webmail importer to bring your real world professional relationships online and to find your contacts who are already on LinkedIn.
•    Depending on whether you’re a browser person or an Outlook person, check out the respective toolbars that will help organize your professional relationship either while you browse or check out your Inbox.

These are just a few tips that I’ve gleaned from my LinkedIn usage over the past year. If you’ve other tips that have helped you as a job seeker reach out to appropriate hiring managers or recruiters, feel free to leave a comment. Hope this helps.

VN:F [1.9.6_1107]

Rating: 3.3/5 (3 votes cast)
VN:F [1.9.6_1107]
Rating: +1 (from 1 vote)