Showing posts with label SQL Server. Show all posts
Showing posts with label SQL Server. Show all posts

Optimize SQL Using SET ROWCOUNT

Posted by Techie Cocktail | 2:19 PM | | 5 comments »

SET ROWCOUNT causes SQL Server to stop processing the query after the specified number of rows are returned.

Once the ROWCOUNT is set then the following queries would return those many number of rows in the resultset irrespective of any filtering or conditions applied.

To turn off this option, set the ROWCOUNT to 0. This command can be executed by any
users. The user need not have any special permissions to execute this command.


Syntax:
SET ROWCOUNT <number> | <@number_var>

It is the best way to optimize a query, if we are aware of how many records we would
need at a time. For example, if you are performing custom paging for GridView in
asp.net 2.0, then you can set the query to return only the required number of rows as set in the PageSize property of the GridView.

Visit MSDN for more details with examples: MSDN

In the LINQ to SQL Overview, we saw the internals of LINQ to SQL with a simple example showing how to retrieve data from SQL. In this article we will see how to insert and delete records in a SQL table using LINQ to SQL.

Lets take the same example as in the Overview article and insert to and delete records from the Countries table.

Insert Records

To insert records to the table, the LINQ provides two methods -
InsertOnSubmit() - Used insert single record to the database.
InsertAllOnSubmit() - Used to insert multiple records to the database.

These inserts are actually commited to the database when SubmitChanges() method of the DataContext is called. Lets insert Australia, Germany & Russia to the Countries table.

Note: The insert, delete and update operations won't work if the table does not have a primary key set.


public static void InsertCountries()
{
//Create the Countries DataContext object.
CountriesDataContext _countriesDataContext = new CountriesDataContext();

//Create the List of type Country.
//This list would contain the new countries that we will insert in the database.
List lstCountry = new List();

//New country objects
Country _1stCountry = new Country();
_1stCountry.CountryId = 7;
_1stCountry.CountryName = "Russia";
lstCountry.Add(_1stCountry);

Country _2ndCountry = new Country();
_2ndCountry.CountryId = 8;
_2ndCountry.CountryName = "Germany";
lstCountry.Add(_2ndCountry);

Country _3rdCountry = new Country();
_3rdCountry.CountryId = 9;
_3rdCountry.CountryName = "Australia";
lstCountry.Add(_3rdCountry);

//Use InsertAllOnSubmit method to insert the new country list.
_countriesDataContext.Countries.InsertAllOnSubmit(lstCountry);

//Commit to the database.
_countriesDataContext.SubmitChanges();
}


Delete Records

To delete records, we use DeleteOnSubmit() or DeleteAllOnSubmit() methods followed by SubmitChanges() method of the DataContext.

Lets delete few countries from the Country table. Lets say, we want to delete all the countries with CountryId > 5.


public static void DeleteCountries()
{
CountriesDataContext _countriesDataContext = new CountriesDataContext();

var cntries = from c in _countriesDataContext.Countries
where c.CountryId > 5
select c;

_countriesDataContext.Countries.DeleteAllOnSubmit(cntries);
_countriesDataContext.SubmitChanges();
}


There are many insert, delete or update scenarios that people can encounter. MSDN provides good reference - LINQ to SQL Samples covering most of the scenarios.

LINQ to SQL Overview

Posted by Techie Cocktail | 4:49 PM | , | 1 comments »

Introduction

Now what is this new thing? As we all know that every day we have something new coming up. It is the new way to access data from the SQL. LINQ to SQL got introduced in VS 2008, .Net Framework 3.5. Hence update your visual studio to this version before you can work on LINQ to SQL.

First thing before we start, Please forget everything about ADO.Net concepts so that you don't try to relate any of its concepts with LINQ to SQL internals.

Overview

LINQ to SQL uses an Entity-based Framework. It uses a DataContext that contains one or more entity classes. These classes contain public properties that map to each column of the database table that they map to. When we execute LINQ to SQL queries and retrieve data from database, instances of these entity objects get created for each row in that SQL table. You do not have to do all this work, the whole process is internally taken care by the DataContext object.

If you are new to LINQ to SQL, you may not understand some of the above mentioned
terminologies. In short, DataContext is required which helps retrieve data from the
database and also submits our changes back to the data to the database.

Lets see a step-by-step example and relate to what we have read.

Example

a. Lets say we have a Countries table in SQL as below. We will use LINQ to SQL query to retrieve the countryName values from Countries table.



Here we will work on a simple console application mainly to display the data that we retrieve using LINQ to SQL.

b. Add new item to the project called 'LINQ to SQL Classes'. This creates a .dbml file. Select the .dbml file to load the Object Relational Designer (ORD). Drag and drop the Countries table from Server Explorer to the ORD.



As we dropped the Countries table, it creates the Countries DataContext underneath (can be viewed in Countries.designer.cs file). Using the instance of this DataContext object we can read and update data to and from the database.

As we see above, the Country Entity class gets created and it has public properties that map directly to the columns of Countries table. In our code we would use this entity class that stores the data retrieved from SQL table using the CountriesDataContext.

c. Sourcecode:


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace linqtosql
{
class Program
{
static void Main(string[] args)
{
GetCountries();
}

Public static void GetCountries()
{
//Create instance of the Countries DataContext class.
CountriesDataContext _countriesDataContext = new CountriesDataContext();

try
{
//Prepare the query to retrieve the data from Countries table
var resCountries = from c in _countriesDataContext.Countries
select c;

//Execute the SQL Query and print the CountryName values

//Also here the CountryDataContext creates
//instances of Country class with data values for each row of data
//in the Countries table.
foreach (var resCountry in resCountries)
{
Console.WriteLine(resCountry.CountryName);
}
Console.Read();
}
catch (Exception ex)
{
Console.Write(ex.Message);
Console.Read();
}
}
}
}


Optional

This is one way of creating DataContext and the Entity Classes. You can also create them on your own, without any tool. Refer http://msdn.microsoft.com/en-us/library/bb386940.aspx for more information about creating manually DataContext & Entity Classes, map them to the database table and query to get the data in the similar way as above.

In the next article we will see some of the common SQL-like operations using LINQ to SQL like how to insert, update, delete, and read using filters, sorting, grouping.

References: http://msdn.microsoft.com/en-us/library/bb386976.aspx

If you are using Windows Vista OS & SQL Server 2005 on your local system and if you are having a hard time to connect to <Machine-name>/SQLEXPRESS SQL Server with error message - "Can't connect to SQL Server", then the culprit is SQL Express 2005 SP1.

Download SQL Express 2005 SP1 from the below site and try reconnecting, you will say c'mon, don't tell me this was the issue :)

http://www.microsoft.com/downloads/details.aspx?FamilyId=11350B1F-8F44-4DB6-B542-4A4B869C2FF1&displaylang=en

Split Function in SQL Server

Posted by Techie Cocktail | 1:43 PM | | 0 comments »

Did you ever want to split a comma/space/<any character> delimited long string?
In .Net we have the in-built split function available to perform this task.

Check this below function in SQL Server:


CREATE FUNCTION dbo.splitString(
@sInputList VARCHAR(8000) -- List of delimited items
, @sDelimiter VARCHAR(8000) = ' ' -- delimiter that separates items. Space in this case.
) RETURNS @List TABLE (item VARCHAR(8000))

BEGIN
DECLARE @sItem VARCHAR(8000)
WHILE CHARINDEX(@sDelimiter,@sInputList,0) <> 0
BEGIN

SELECT @sItem=RTRIM(LTRIM(SUBSTRING(@sInputList,1,CHARINDEX(@sDelimiter,@sInputList,0)-1))), @sInputList=RTRIM(LTRIM(SUBSTRING(@sInputList,CHARINDEX(@sDelimiter,@sInputList,0)+LEN(@sDelimiter),LEN(@sInputList))))

IF LEN(@sItem) > 0
INSERT INTO @List SELECT @sItem
END

IF LEN(@sInputList) > 0
INSERT INTO @List SELECT @sInputList -- Put the last item in
RETURN
END
GO

-- This is how you would test
select * from splitString('This is a split function', ' ')

-- Output
This
is
a
split
function


References: http://searchwindevelopment.techtarget.com/tip/0,289483,sid8_gci932171,00.html