SQL Like Statement (or) Condition is basically used for checking if a particular charter string appears in a given string or not. We can use wildcard symbols in the where clause and also in the CASE Statements for pattern matching. Because of this, the SQL Like operator is more powerful than using the equal to (=) or not equal to (! =) symbols for pattern matching and more generically for string comparison. The basic point that we need to keep in mind while using the SQL Like operator is; the result set returned by it is a Boolean value, meaning a TRUE or FALSE.

SQL Like Syntax

The basic syntax for SQL Like is shown below.

match_expression [ NOT ] LIKE pattern [ ESCAPE escape_character ]

SQL Like – Wildcards

The following are the wildcards that can be used with the SQL like condition – %( Percentage symbol), _ (Underscore), [] (Square Parenthesis), ^ (Caret symbol); will show each of them with examples…

Firstly, let us create a temporary table and insert some data into it and see how we can use the SQL Like operator.

CREATE TABLE #SQL_Like (NameID int, ContactName nvarchar(50))

 INSERT INTO #SQL_Like  Values (1,'Amy')
 INSERT INTO #SQL_Like  Values (2,'Anna')
 INSERT INTO #SQL_Like  Values (3,'Brenda')
 INSERT INTO #SQL_Like  Values (4,'Catherine')
 INSERT INTO #SQL_Like  Values (5,'Daniel')
 INSERT INTO #SQL_Like  Values (6,'Emilio')
 INSERT INTO #SQL_Like  Values (7,'Edna')
 INSERT INTO #SQL_Like  Values (8,'Frances')
 INSERT INTO #SQL_Like  Values (9,'Gustavo')
 INSERT INTO #SQL_Like  Values (10,'Hannah')
 INSERT INTO #SQL_Like  Values (11,'Ian')
 INSERT INTO #SQL_Like  Values (12,'John')

Examples for using SQL Like Condition

The most basic form to start with, suppose from the above table if we want to get all the names starting with “A” we can use the below query.

SELECT * FROM #SQL_Like  WHERE ContactName Like 'A%'

The “%” percentage wild card is used for doing a pattern match of any string of zero or more characters. And this is the result that we would get once we are done with executing the above line of T-SQL.

NameID ContactName

1          Amy

2          Anna

If we want to get a list of names that end with “A”, we can use the same wild card, but we will have to put it in the front and the letter that we want to search for at the end, shown like the below.

SELECT * FROM #SQL_Like  WHERE ContactName Like '%A'

And the result for the same would be

NameID ContactName

2          Anna

3          Brenda

7          Edna

Suppose, if there is a requirement where we know that we need to look into the names, in whose name the 2nd letter is “A”, then we have to write a query like the below, the “_” underscore wild card symbol denotes a single character.

SELECT * FROM #SQL_Like  WHERE ContactName Like '_A%'

And the result for the same would be

NameID ContactName

4          Catherine

5          Daniel

10         Hannah

11         Ian

Say, if we want to search for a name, which starts with “A” and in which the second alphabet is something between “A” and “M”, then our result has to be the first name that we had inserted, i.e “Amy”. For this we actually use the “[ ]” square brackets, they are used for searching any single character within the specified range ([a-g]) or set ([abcdefg]).

SELECT * FROM #SQL_Like  WHERE ContactName Like A[A-M]%'

Using SQL NOT Like

Till now we have seen how to directly use the “Like operator”. Now we shall take up an example where we will add “Not” in front of our “Like”. For this, the example that we can take is, say we need a list of all the name’s that do not have the alphabet “A” in them, then our query would resemble the below.

SELECT * FROM #SQL_Like  WHERE ContactName NOT Like '%A%'

Using SQL Like Escape Clause

Everything seems to be fine till now, so, let’s think like this, the wild card symbols are really cool, but what if I need to look into a string for those wild card character’s, puzzled!!!

For this we have these escape clause J. Check the syntax at the beginning of the article
In the below example, my escape character is “!”, so I am actually trying to search for John%, of course practically no names will exist in this way unless there is a type!!! This is just for the sake of taking an example and looking at on how to use it

SELECT * FROM #SQL_Like  WHERE ContactName LIKE '%John!%%' ESCAPE '!'

Let’s take one more example, here we want to look for the underscore symbol, and that’s a wildcard symbol, so decide to make use of the Escape clause over here as well.

SELECT * FROM #SQL_Like  WHERE ContactName LIKE '%John!_%' ESCAPE '!' 

The basic thing over here is that we need to look for a symbol that can be used in the escape clause, means something, that does not exist in our string.

Using SQL Like with Variables and Expressions
We can use the SQL LIKE operator with Variables and Expressions, they can combination of alphabets, alphabets and alpha-numeric, a query with scalar output, a varchar or nvarchar type local variable. But, remember one thing, at the end, everything would be looked at as a string(Not char) by the sql server.

The below is a self-explanatory code snippet. Firstly, we are declaring a variable, then we are setting it to a string “la” and then we are searching for it in the names. In the first, example we are trying to search for characters in the start of the name and in the second example we are trying to search for the characters in the end of the name

DECLARE @Name nvarchar(2)
 SET @Name ='Ia'
 SELECT * FROM #SQL_Like  WHERE ContactName Like @Name +'%'

DECLARE @Name nvarchar(2)
 SET @Name ='N'
 SELECT * FROM #SQL_Like  WHERE ContactName Like '%'+ @Name

Using SQL Like with Case Statement
As stated earlier, the sql like condition returns a true or false, so we can use this in multiple scenarios in conjunction with a CASE statement. Here in the below code snippet we are actually trying to find all the names that start with A, B. We can also construct similar thing where the condition can equal to 0.

SELECT * FROM #SQL_Like
 WHERE CASE
 WHEN ContactName LIKE 'A%' THEN 1
 WHEN ContactName LIKE 'B%' THEN 1
 END = 1

{ Comments on this entry are closed }

There are many instances when we want to get a list of all the columns in a database (or) find a particular column in a database, not sure in which table it is!!! OR the case may be even we want to find a column whose prefix or suffix may be know to us.

Instead of manually searching for column, we can query the sql server system tables and find that information.

Here is the query, you can just run it and see the results by your self. Actually it is selecting data from three system catalogs; Schemas, Objects and Columns. You can also try out selecting data from them individually and see what they return, these are really useful.Here, in the where clause I have put condition to get data for User Tables (U) and Views (V).

SELECT S.name as SchemaName,O.name as ObjectName, O.type_desc as ObjectType,C.name
FROM sys.schemas S
INNER JOIN sys.objects O ON S.schema_id=O.schema_id
INNER JOIN sys.columns C ON O.object_id=C.object_id
WHERE O.type in('U','V')
ORDER BY S.name,O.type_desc, O.name,C.Name

And here is how you may be seeing the result.

SQL Server Find Column Name in Database

{ Comments on this entry are closed }

There is a free webinar for SQL DBA’s from PragmaticWorks on “Intro to .NET for DBA” .

“In this session, Ben will show you a basic overview of developing with C# presented from the perspective of a DBA. This webinar will provide basic information on the .Net framework as well as how to present data, and best practices which DBA’s can look out for from there developers”

If you are interested, please register for it over here.

For your Information – It is at India Time 9.30 PM on Tuesday Night of 01 March 2011.

{ Comments on this entry are closed }

This was forwarded by one of my friends, a very nice story….!!!!
An old man lived alone in Minnesota. He wanted to spade his potato garden, but it was very hard work. His only son, who would have helped him, was in prison. The old man wrote a letter to his son and mentioned his
Situation:
 
Dear Son,
 
    I am feeling pretty bad because it looks like I won’t be able to plant my potato garden this year. I hate to miss doing the garden, because your mother always loved planting time. I’m just getting too old to be digging up a garden plot. If you were here, all my troubles would be over. I know you would dig the plot for me, if you weren’t in prison.
 
Love,
Dad
 
    Shortly, the old man received this telegram: “For Heaven’s sake, Dad, don’t dig up the garden!! That’s where I buried the GUNS!!”
 
    At 4 a.m. the next morning, a dozen FBI agents and local police officers showed up and dug up the entire garden without finding any guns. Confused, the old man wrote another note to his son telling him what happened, and asked him what to do next.
 
    His son’s reply was: “Go ahead and plant your potatoes, Dad. It’s the best I could do for you from here.”
 
Moral:
 
    No Matter Where You Are In The World, If You Have Decided To Do Something Deep From Your Heart You Can Do It. It Is The Thought That Matters Not Where You Are Or Where The Person Is.

{ Comments on this entry are closed }

While working with the script component in SSIS, sometimes we may run into the below warning. 

Warning           XX       ‘ScriptMain’ is not CLS-compliant because it derives from ‘UserComponent’, which is not CLS-compliant.

And an error like,

Error XX Validation error.DdataFlowTaskName Script Component [842]: Microsoft.SqlServer.Dts.Pipeline.CannotCreateUserComponentException: Cannot create user component class. Make sure there is one class marked with SSISScriptComponentEntryPointAttribute in your script.     at Microsoft.SqlServer.Dts.Pipeline.ScriptComponentHost.CreateUserComponent()

This basically happens because “UserComponent” that we inherit from is not CLS (Common Language Specification) compliant. As per MSDN “A class or interface is marked as <CLSCompliant(True)> when it derives from or implements a type that is marked as <CLSCompliant(False)> or is not marked.”

 So, this issue can be easily rectified easily by adding the below code near the ‘ScriptMain’ line 

<Microsoft.SqlServer.Dts.Pipeline.SSISScriptComponentEntryPointAttribute()> _

<CLSCompliant(False)> _

Public Class ScriptMain

Inherits UserComponent

And also just check the number of input columns being passed and if there are any duplicate columns getting into the script component. This should resolve the issue being faced.

{ Comments on this entry are closed }

People coming from other programming languages to any SQL based language will know how GO TO works in general, even with SQL Server, it is nearly the same.

Go To statement makes the execution of the T-SQL batch to jump and go to a “pre-defined” label. The term pre-defined is important over here, go to statement abruptly makes the code to jump to a label without executing any lines after it, unless the label is next to the Go To line….

We can embed Go to in any of the conditional control-of-flow statements, statement blocks, or procedures but, in practice it is not practical to make much use of this statement as too much of it would not make to code readable and understandable by humans!!! But one thing is, if we have no other choice other than to use this statement then we have to just go ahead using it.

The below is an example from BOL on how to use the GOTO statement, it shows us on how it can be used and how the calls can be made using it, not that the second branch would never be execute because of the condition that is there.

DECLARE @Counter int;

SET @Counter = 1;

WHILE @Counter < 10

BEGIN

SELECT @Counter

SET @Counter = @Counter + 1

IF @Counter = 4 GOTO Branch_One --Jumps to the first branch.

IF @Counter = 5 GOTO Branch_Two  --This will never execute.

END

Branch_One:

SELECT 'Jumping To Branch One.'

GOTO Branch_Three; --This will prevent Branch_Two from executing.

Branch_Two:

SELECT 'Jumping To Branch Two.'

Branch_Three:

SELECT 'Jumping To Branch Three.'

And the below is with a small alter to the above code just showing that we can have a GO TO call/ the Label’s anywhere, there is no precedence.


DECLARE @Counter int;

SET @Counter = 1;

Branch_One:

SELECT 'I am above the GOTO Call'

GOTO Branch_Three; --This will prevent Branch_Two from executing.

WHILE @Counter < 10

BEGIN

SELECT @Counter

SET @Counter = @Counter + 1

IF @Counter = 4 GOTO Branch_One --Jumps to the first branch.

IF @Counter = 5 GOTO Branch_Two  --This will never execute.

END

Branch_Two:

SELECT 'Jumping To Branch Two.'

Branch_Three:

SELECT 'I am below the GOTO Call'

{ Comments on this entry are closed }

This post takes us through on how to query a excel file from SQL Server, doing this using the distributed queries.

Firstly, make sure that the “Run_Value” is set to “1” for “Ad Hoc Distributed Queries”

 

sp_configure 'Ad Hoc Distributed Queries','1'

GO

RECONFIGURE

GO 

 

The below is the result that we are going to get, and we can confirm the change of the configured value by again running sp_configure ‘Ad Hoc Distributed Queries’

 Configuration option ‘Ad Hoc Distributed Queries’ changed from 0 to 1. Run the RECONFIGURE statement to install.

If we do not do this, we will end up getting an error like the below.

Ad hoc access to OLE DB provider ‘Microsoft.Jet.OLEDB.40′ has been denied. You must access this provider through a linked server.””

We can query data by using either of the OPENDATASOURCE or OPENROWSET to query the excel directly.

SELECT * FROM OPENDATASOURCE('Microsoft.Jet.OLEDB.4.0',

'Data Source=C:\test\Excel2Sql.xls;Extended Properties=Excel 8.0')...[Sheet1$]

 SELECT * FROM OPENROWSET('Microsoft.Jet.OLEDB.4.0',

'Excel 8.0;Database C:\test\Excel2Sql.xls', [Sheet2$])

We need to make sure that the source excel file is accessible, means we need to give the correct location, and also we need to make sure that the excel file is not open during this select process, if it is open we would generally get the below error.

OLE DB provider “Microsoft.Jet.OLEDB.4.0″ for linked server “(null)” returned message “Unspecified error“.”

Cannot initialize the data source object of OLE DB provider “Microsoft.Jet.OLEDB.4.0″ for linked server “(null)”.”

Note: – we cannot use this method on a 64 bit OS System, running 64 bit SQL SERVER

{ Comments on this entry are closed }

I have a table where I do logging for all the SQL Server Jobs, I had a requirement where I had to calculate the idle time between two jobs to find the load on the server and better utilise the idle time of the server for other maintenance related operations, for a Job I track many parameters, but the once that are interested for me now for this query are the Job Start Time and the Job End Time, . That is I had to calculate time difference between the last job end time to the current job start time.

 For example, in the below table, I need to know the time difference between the Job End Time for Job ID 1 and Job Start Time of Job ID 2, that’s 120 minutes.

 JobID   JobStartTime                            JobEndTime

1          2011-01-07 02:55:00.000        2011-01-07 03:55:00.000

2          2011-01-07 05:55:00.000        2011-01-07 06:55:00.000

3          2011-01-07 08:55:00.000        2011-01-07 09:55:00.000

 Let me create a temporary table and show how I did it.

CREATE TABLE #JobLog(

JobID int identity(1,1), JobStartTime DATETIME,JobEndTime DATETIME)

INSERT INTO #JobLog(JobStartTime,JobEndTime)

VALUES('2011-01-07 02:55:00.000','2011-01-07 03:55:00.000')

INSERT INTO #JobLog(JobStartTime,JobEndTime)

VALUES('2011-01-07 05:55:00.000','2011-01-07 06:55:00.000')

INSERT INTO #JobLog(JobStartTime,JobEndTime)

VALUES('2011-01-07 08:55:00.000','2011-01-07 09:55:00.000')

 

Checking for table and it’s records.

SELECT * FROM #JobLog

Time difference between Last Job End Time and Current Job Start Time

WITH CTE as(

SELECT JobID, JobStartTime, JobEndTime, (

    SELECT MAX(T1.JobEndTime)

    FROM #JobLog T1

    WHERE T1.JobEndTime < T2.JobStartTime

  ) AS Previous_JobEndTime

  FROM #JobLog T2

 )

SELECT JobID, JobStartTime, JobEndTime

      , DATEDIFF(MI,Previous_JobEndTime,JobStartTime) AS IdleTime

FROM CTE

 

 And the below is the resuly.

JobID   JobStartTime                            JobEndTime                             IdleTime

1          2011-01-07 02:55:00.000        2011-01-07 03:55:00.000        NULL

2          2011-01-07 05:55:00.000        2011-01-07 06:55:00.000        120

3          2011-01-07 08:55:00.000        2011-01-07 09:55:00.000        120

dropping the temporary table

DROP TABLE #JobLog

{ Comments on this entry are closed }

New Year???

January 4, 2011

in Personal

I am trying to understand on what’s so good about the New Year; does it automatically do all the good to us?

Did we live any differently on December 30th and Jan 2nd?

New Year is just a mere change of date, unless we strive to make a change in the way we are going to live on this earth, the way we behave with our near and dear, our thought process and just about everything in our day to day life’s.

No good can happen if we are going to live the same way as we have always been doing…

{ Comments on this entry are closed }

Recently, I had installed Denali, and the first thing I tried to do on it was getting the AdventureWorks data base on that. The MDF File of the database is available for download from CodePlex , http://msftdbprodsamples.codeplex.com/releases/view/55330 .

The below is the code to attach the MDF file downloaded.

CREATE DATABASE AdventureWorks2008R2

ON (FILENAME = ‘ C:\Denali\AdventureWorks2008R2_Data.mdf’)

FOR ATTACH_REBUILD_LOG ;

While trying to attach the database, I ran into a few issues, got the below error

Msg 5120, Level 16, State 101, Line 3 Unable to open the physical file “C:\Denali\AdventureWorks2008R2_Data.mdf”. Operating system error 5: “5(Access is denied.)”.

Then I fixed the security settings, this is a basic problem with the sql server account running and some other credentials which do not have access to the particular drive location and (or) the particular user account who is running the commands does not have enough permissions on the system.

Then I was successfully able to attach the file and got the below

File activation failure. The physical file name “C:\Program Files\Microsoft SQL Server\MSSQL11.MSSQLSERVER\MSSQL\DATA\AdventureWorks2008R2_Log.ldf” may be incorrect.

New log file ‘C:\Denali\AdventureWorks2008R2_log.ldf’ was created.

Converting database ‘AdventureWorks2008R2′ from version 679 to the current version 684.

Database ‘AdventureWorks2008R2′ running the upgrade step from version 679 to version 680.

Database ‘AdventureWorks2008R2′ running the upgrade step from version 680 to version 681.

Database ‘AdventureWorks2008R2′ running the upgrade step from version 681 to version 682.

Database ‘AdventureWorks2008R2′ running the upgrade step from version 682 to version 683.

Database ‘AdventureWorks2008R2′ running the upgrade step from version 683 to version 684.

SQL SERVER – Installing AdventureWorks for SQL Server 2011(Denali)

{ Comments on this entry are closed }