Different Behavior of @@ROWCOUNT with Set,Print and Set NoCount On.

Few days back someone ask to me why a sql server global variable  @@RowCount produce different output for different-different set of queries in  store procedure.

Below is a simplified version of the query, can you tell why @@Rowcount will be 0?

  1. When Print Statements used before accessing the @@RowCount Variable.r1

Think what will be the output produce from print and select statements which are used at line number  12.

images

Are you thinking about 3 as there are 3 entries in a table.if you are thinking in this direction then it is completely wrong.

Answer:if you run complete query then value of variable @showcount will be 0.

Why:because print resets the value of @@ROWCOUNT to 0 and the same  value assigned to @showcount parameter.So that @Showcount returns 0 .

so it is recommended that  print statements should not be used before @@RowCount variable.if you are doing so then you always get surprise output which will not be as per expectation.

So best practices says,do not use any  other query  before @@RowCount variable and use local variables to hold the value of @@RowCount.Do not include  global variables directly in your business logic.

Statements that make a simple assignment always set the @@ROWCOUNT value to 1. No rows are sent to the client. Examples of these statements are: SET @local_variable, RETURN, READTEXT, and select without query statements such as SELECT GETDATE() or SELECT ‘Generic Text’.

Correct way to use @@RowCount:

If you want to store the rows that were affected by A DML statement then you need to grab @@ROWCOUNT immediately after the DML statement. There can’t be any code between the DML statement and your code that stores @@ROWCOUNT into a variable.

Here i am using same query as i mentioned top of the article with little bit changes to make query more feasible.

R2.JPGNow you can see that output is 3  and it is as per expectations. Because i have moved print statement just after the reading the @@RowCount variable.

There are more intersting facts about @@RowCount variables:

  1. IF statement also resets the @@ROWCOUNT and you get back 0.Try below query:
DECLARE @ShowCount INT
 
SELECT 1
UNION all
SELECT 2
 
if 1=1
SELECT @ShowCount = @@ROWCOUNT
 
SELECT @ShowCount

2. Set Statements also reset the @@ROWCOUNT and you get back 1.

Script:

Select 1 as output
union All
select 2 as output

Declare @Flag bit
Set @Flag=1

select @@ROWCOUNT as TotalRecords

OutPut:

r3

Again Surprise output,as per the select statement @@Rowcount should retuns 2 becuase UNION ALL used with both select statements but @@RowCount returns 1.

this happens due to Set statement is used just before accessing the value of @@RowCount.So set statement reset the counter to 1 so that different output produce by the sql engine.

 

There are many more statements for which @@ RowCount differently as per the expectation.

Statements such as USE, SET <option>, DEALLOCATE CURSOR, CLOSE CURSOR, BEGIN TRANSACTION or COMMIT TRANSACTION reset the ROWCOUNT value to 0

 

Advertisements

What is UDL(Universal Data Link)

One of the most common problem in any data driven application working is the database connection string. How many times in your development life have you heard “I can’t connect to the database” and the problem ends up a minor detail in the connection string?

“How to verify sql server connection without SSMS?” or “How to find installed sql server instance names on a machine without SSMS or any tools?”

The Microsoft Data Access Components (MDAC) provide the Data Link Properties dialog box as the common user interface for specifying connection information to a data provider on Windows 2000 and later operating systems. You can use the Data Link Properties dialog box to save connection information in a universal data link (.udl) file.

To create a Universal Data Link (.udl) file

  • RUN → Notepad
  • Once the notepad is opened, File → Save As… (Do not type anything in the notepad)
  • Choose the path → Save as type: All Files (*.*) → File name: Rakesh.udl (File name can be anything but the extension must be .udl)

U1

  • Double click on the udl file.

U2

  • Select provider name for whatever you want test database connection.here  “Microsoft OleDb Provider for SqlServer” is used for testing.
  • Now go to the Connection tab and select the database to connect to. You may just browse through the list but SQLExpress instances do not always show up. You may also type the server name into the list box. select appropriate authentication mode(windows or sqlserver).
  • Now you will see all databases in drop down and select any one database.
  • Assuming all’s well, select the database and click the Test Connection button.

U5.JPG

  • Now open the file in notepad – remember, the .udl file is simply a text file. You should see something like this:

U6.JPG

 

In the file is the connection string you just tested. Copy and paste were needed in your application and you should be good to go.

Lazy Loading vs. Eager Loading

Download complete project : LazyLoadingEagerLoading.zip

The Entity Framework offers several different ways to load the entities that are related to your target entity. For example, when you query for Employee, there are different ways that the related Employee Addresses will be loaded into the Object State Manager. From a performance standpoint, the biggest question to consider when loading related entities will be whether to use Lazy Loading or Eager Loading.

When using Eager Loading, the related entities are loaded along with your target entity set. You use an Include statement in your query to indicate which related entities you want to bring in.

  • Lazy Loading – “don’t do the work until you absolutely have to.”

When using Lazy Loading, your initial query only brings in the target entity set. But whenever you access a navigation property, another query is issued against the store to load the related entity that means Related/child objects are not loaded automatically when a navigation property is accessed.Once an entity has been loaded, any further queries for the entity will load it directly from the Object State Manager. you can also turn off lazy loading for a particular property or an entire context. To turn off lazy loading for a particular property, do not make it virtual. To turn off lazy loading for all entities in the context, set its configuration property to false:

this.Configuration.LazyLoadingEnabled = false;

Rules for lazy loading:
  1. context.Configuration.ProxyCreationEnabled should be true.
  2. context.Configuration.LazyLoadingEnabled should be true.
  3. Navigation property should be defined as public, virtual. Context will NOT do lazy loading if the property is not defined as virtual.

Let’s start with actual implementation.Create Console Application with name LazyEagerLoading.

Lazy Loading

Step 1: Create Poco classes for employee and employeeAddress. PocoClassesaddresses Step 2: Create EmployeeContext and EmployeeDbInitilizer classes. Dbcontext DbInitilizer Step 3: As per the above code, i am trying to get employee details using the employeecontext class and then iterate through the employee item also try to read navigation property EmployeeAddresses. If you try to debug the code and find  that details for parent and child related tables comes at one time but this is not correct.Actually some thing different activity happens at back end and there are several sql query executed to get the details and to track this activity  i have used  sql profiler. you can see code for lazy loading and outcome of the code: LPLazyOutput

 

Now run the application. In the code above, note the first for-each loop, the data of only the main entity, the Employee, is loaded but not that of the EmployeeAddresses. The data of the related entity is loaded when the nested foreach loop is executed. Analysis report of sql profiler for above code execution: LazyProfiler Here you can see that there are four different queries executed to fetch the details from the database. first query executed to get employee details and other three queries executed to fetch the details of navigation property that is EmployeeAddress.This means that to fetch the data of the related entity, database calls are being made again and again, after the data for main entity has been fetched, that could negatively hamper the efficiency of the application.

EagerLoading: Step 4: To implement the eager loading we have to make two changes in our existing code. first change in employeeContext class and second in our program.cs . Add below statement in employeeContext constructor:

this.Configuration.LazyLoadingEnabled = false;

LazyLoadingEnalbled property set to false disable lazy loading and allow to fetch related entity data  using “Include” when the main entity load in memory. Eagercontext

Step5 : Include related entity with main entity at the time of query execution. Snippet

var query = ContextObj.Employees.Include("EmployeeAddresses").ToList();

eProgram

Step 6: Now again execute above code,see output and track background process with sql profiler. now you can see output is still same as lazy loading but there is a major difference in sql profile analysis report. this time only single query executed to get the parent and child entity details while in lazy loading example different queries initiate to fetch the details. LazyOutput etrace

 

You will see the query at the bottom of the selection that shows the join being applied at the back-end by the SQL Server. This is known as Eager Loading which means loading the related entity data along with the data of the main entity. Now the question arises when to use what option:

Do you need to access many navigation properties from the fetched entities?

No Both options will probably do. However, if the payload your query is bringing is not too big, you may experience performance benefits by using Eager loading as it’ll require less network round trips to materialize your objects. Yes If you need to access many navigation properties from the entities, you’d do that by using multiple include statements in your query with Eager loading. The more entities you include, the bigger the payload your query will return. Once you include three or more entities into your query, consider switching to Lazy loading.

Do you know exactly what data will be needed at run time?

No Lazy loading will be better for you. Otherwise, you may end up querying for data that you will not need. Yes Eager loading is probably your best bet; it will help loading entire sets faster. If your query requires fetching a very large amount of data, and this becomes too slow, then try Lazy loading instead.

Is your code executing far from your database? (increased network latency)

No When the network latency is not an issue, using Lazy loading may simplify your code. Remember that the topology of your application may change, so don’t take database proximity for granted. Yes When the network is a problem, only you can decide what fits better for your scenario. Typically Eager loading will be better because it requires fewer round trips.

One Step To Understand Relationship Of Primary Key And Non-Clustered Indexes.

Keys and indexes are key fundamental concepts of any RDBMS and play very crucial rule to design good and efficient database. If you have to design performance oriented database then you should have to implement keys and indexes in proper manner in your database.

Developers often do not specify which column should have clustered index. As we know by default Primary Key becomes Clustered Index but vice versa is not true that means you can create clustered index on non primary key column also. This practice is now extremely common and lots of people have forgotten that Primary Key and Clustered Index are two different things.

Another common misconception most people have is “Creating a primary key on a table makes reads fast”.

I want to clarify, Primary key is a constraint, and it has nothing to do with fast reads. “Primary Key” behind the scenes creates a clustered Index which makes the reads fast. Optionally we can also create non-clustered for primary key which contributes to faster reads.

One common and simplest question asked by any interviewer that “what is a Primary key” and most of us reply very quickly with following facts:

  • The primary key constraint uniquely identifies each record in a database table.
  • Primary keys must contain unique values.
  • A primary key column cannot contain NULL values.
  • Most tables should have a primary key, and each table can have only ONE primary key.

But there are few more questions comes in mind about the primary key and indexes as per below:

  1. Can we create primary key and clustered index two different columns?
  2. Is it mandatory to create clustered index on primary key?
  3. Can we create non-clustered index on primary key?

These are the question that creates the confusion and most of the candidates are not confident to say anything.

First of all we have to remember below statement and always keep in mind.

“Primary Key can be clustered or Non-clustered but it is a common best practice to create a Primary Key as Clustered Index. “

In short we can create primary key and clustered index in two different columns and it is not mandatory to apply both of things in same column.

It is not also mandatory to create clustered index on primary key and clustered index can be created on non primary column.

Yes definitely non-clustered index can be created on primary key.

There are following scenario about primary key and Clustered Index:

1. Primary key default to Clustered Index:

This is common scenario in which developers always create primary key and clustered index automatically apply on primary key column. There is no explicitly need to create clustered index on primary key column.

This is a main reason that developers not aware that primary key and clustered index are two different things.

1

You can see in above output result that clustered index is created automatically whenever primary key applied but always remember that vice-verse is not true.

2. Primary key default to Non-Clustered Index:

This is not mandatory that primary key and clustered key is co-related to each other and clustered index only created on primary key. In this scenario we will explicitly defined Primary Key as a non-clustered and it will create it as a non-clustered index.

You can clearly identify that non-clustered index is created on primary key and stored in Heap.

 2

Note: Heaps (Tables without Clustered Indexes) A heap is a table without a clustered index. One or more no-clustered indexes can be created on tables stored as a heap. Data is stored in the heap without specifying an order.

3: Primary Key defaults to Non-Clustered Index with another column defined as a Clustered Index.

In this scenario we will explicitly defined unique Key as a clustered index and another primary key column automatically assign a non-clustered key. It means if any table already have clustered index and primary key is created on the table then by default non-clustered index created on primary key.

3

In above result we can see that no clustered key is created on primary key while clustered key is created on unique key column.

4: Primary Key defaults to Clustered Index with other index defaults to Non-clustered index.

If any table has primary key and unique key and not applied any index explicitly then in this case clustered key is goes with primary key column and non-clustered key goes with unique column.

4

As per the above scenarios we can say that primary key is not strictly bound with clustered key. Developers have to apply both of things as per the situation.

To achieve optimal performance, it is better to go with primary key along with clustered key.