Saturday, May 12, 2012

Using Trim() in LINQ to SQL on an Empty string

This is kind of a silly thing I did, now that I think about it, but I must admit I was ignorant.

I didnt realize that you don't necessarily need a string utility to "Trim()" an Empty string of whitespaces, becuause, well, it doesn't matter.

To SQL, ' ' is same as '          '.

What I realized when using Trim() function, was this function was adding an overload of ltrim(rtrim(emptystringfield)) to my already resource intensive query, which in effect was increasing my query execution time. So use Trim() only when you need it, especially when using expensive queries.

Wednesday, April 18, 2012

Searching for numeric character(s) in Column of a Table in SQL

For Reference:

select * from [YourTable] where 
patindex('%[0-9]%',[yourcolumn]) <> 0

That was kinda easy!

Friday, March 23, 2012

Visual Studio Themes

I tweaked my IDE to have a black background v/s the default white, and also changed some other color schemes to have contrasting colors, but here's a website that gives you a good amount of cool themes to apply to. Check out the link below. I am going to try them soon!

http://www.hanselman.com/blog/VisualStudioProgrammerThemesGallery.aspx

Wednesday, March 7, 2012

Deleting duplicate records using SQL

I have been working on SQL lately and its worth mentioning in the blog as to how easily find and delete duplicate records in the database.

Here's a nice solution posted by Pinal Dave on his blog:

http://blog.sqlauthority.com/2007/03/01/sql-server-delete-duplicate-records-rows/


NJoy!

Tuesday, February 21, 2012

Maintaining Scrollbar postion of listBox inside of UpdatePanel

I have this multiple selected ListBox where I would want to maintain the scroll position of the ListBox. This is how I did, following the instructions from the blog post here

Please make sure this code is after the ScriptManager tag on the page:

Wednesday, December 7, 2011

Exporting nvarchar fields from SQL Server to a csv file

I am posting this more so for a reminder for myself to acknowledge myself that there is something called observation.

I am working on this data migration project(like I didnt say that earlier!) and I was exporting firstname and lastname (nvarchar fields) to a csv file and I was having issues on the final export. I was getting the following error:



I searched on the internet to find a solution to it, but couldn't find one. I was feeling frustated. Then I thought there must be something that should solve it.

I went all over again through the sql server export screens and found that little tiny checkbox that my eyes weren't able to catch before:


So I marked the "Unicode" checkbox, and I was able to export all my records successfully!

Moral of the story: Keenly observe the details before banging your head on the monitor!

Tuesday, November 29, 2011

Discarding changes in LINQ memory

I was looking for a solution just like what I used to do with ADO.NET back in the days when LINQ was non-existent.

My issue was that when I received an exception while inserting a row in SQL db (due to duplicate value already present), I wanted to discard that insertion from the memory and carry out with the next insertion. The problem was that the last insertion error was not removed from memory.

Many people suggested recreation of the DataContext object, but that was not an option for me. After some "Googling", I found the link below which was helpful:

http://graemehill.ca/discard-changes-in-linq-to-sql-datacontext

Though I did something like the one below in the catch block, where "spmap" was the new object created for insertion.
datacontext.tablename.DeleteOnSubmit(spmap);
Works for me! :)

Wednesday, November 2, 2011

Handling NULL values in SQL case statements while inserting or Updating Records

I am working on this massive data import project. Reminds me of those old days, when lots of stuff was done at the SQL level and and .NET took care of the UI Side. LINQ spoiled me to do all the SQL stuff using LINQ to SQL.

Anyway, working on SQL console is a lot of fun. Especially for big data imports and exports, that's the way to go. Feels like you are more so of a DBA!

NULL values are always tricky to work with. I came across this problem where I had to write a case statement where if the value is NULL, update the 'remarks' field, else append the value to the field:

Here's what I was doing:
update [tablename]
set remarks=case remarks when null then 'source:ms.csv'
else (remarks + '; source:ms.csv') end
where email='xyz@abc.com'
Apparently, the field was'nt updated since the remarks field was blank for that record. Looks strange!

After doing a little research and trying a few conditions, here's how it worked:
update [tablename]
set remarks=case isnull(remarks,'true') when 'true' then 'source:ms.csv'
else (remarks + ' source:ms.csv') end
where email='xyz@abc.com'

Note that the second parameter should be implicitly convertible to the first parameter of isnull.

UPDATE: April 2012
For numeric/decimal/int columns, this would be it:
update [tablename]
set totalcount=case isnull(totalcount,0) when 0 then 1
else (totalcount + 1) end
where email='xyz@abc.com'

Check the microsft documentation here for details.

Thats how it goes! You can take care of bigger chunks of data, but its the little things like those NULL values that drive you crazy!

Tuesday, September 27, 2011

Using Linq to SQL to fetch the records that non alphabetic

I came across an issue where I had to fetch all the email addresses that do not begin with an alphabet. I learnt something new and interesting today.

On the sql server side, query the database table with something like this:
select * from [yourtable] where [columnname] like '[^a-zA-Z]%'
This interestingly fetches all the desired email address that either begin with a number, or have any other special character.

How to achieve this in Linq? Well that's a little tricky. This was my initial query:
DataClassesDataContext db = new DataClassesDataContext();
     var therecords =    from dh in db.customers
                         where dh.email.StartsWith("[^a-zA-Z]%")
                         select dh)

When this query was executed, it yielded zero results. This was how sql was interpreting the LINQ to Sql query:
exec sp_executesql N'SELECT *
FROM [dbo].[customers] AS [t0]
WHERE [t0].[email] LIKE @p0 ESCAPE ''~''',N'@p0 varchar(12)',@p0='~[~^a-zA-Z]%'

I had to get rid of the Escape characters. Modifying the Linq query as below gave me the desired result:
DataClassesDataContext db = new DataClassesDataContext();
     var therecords =    from dh in db.customers
                         where System.Data.Linq.SqlClient.SqlMethods.Like(dh.email, "[^a-zA-Z]%")                      
                         select dh)

Now I know there is one more way of Linq to get close to Sql!

Thursday, April 7, 2011

Generating Dynamic query for LinqDataSource (Where clause) in code behind

Consider this scenario.

I have a GridView which is binded to a LinqDataSource and it binds the data on the Page_Load Event. Now I have a Search Box, where you would enter the text to be searched in the GridView. The value entered into the search box is searched across x number of columns in the Database table to find a match.

Initially what I did was to generate a new query within the click event handler of the search Button. But when I tried to delete the record after search, it gave me an error:

The GridView 'grdView' fired event RowDeleting which wasn't handled

Apparently this GridView is Binded to the LinqDataSource and upon binding it to a different datasource from Code Behind, there is some data corruption from the results not being properly fetched.

Instead of going further and digging into a solution, I thought about having the where clauses applied for the LinqDataSource right in code behind. Upon doing some research and getting ideas from this blog, I implemented it into my code:


LinqDataSourceSearch.Where = "name.Contains(\"" + txtSearchSponsor.Text.Trim() + "\")";


Pretty easy enough. Right?