Monday, June 24, 2013

Comma separated value in sql query




One of my projects I want to get city postal code as a one column with comma separated. I want two columns as an output. One is State and another one is commas separated postal code in the state.
The below query will help you to get the each state with comma separated postal code.

Code:

SELECT State,
      Post_Code =
        STUFF((SELECT ', ' + Post_Code
           FROM your_table b
           WHERE b. State = a. State
          FOR XML PATH('')), 1, 2, '')
FROM your_table a
GROUP BY State


OUTCOME:
State
Postal_Code
Tamilnadu
600001,600256,638656,638657
Kerala
678965,670059,670056,673598

Saturday, June 15, 2013

WITH Query in SQL


In the sql most of the new developers don’t know how to use  WITH in SQL query.  Its simple and use full for writing big query in the stored procedure. WITH will provide a way of using sub query in the larger select query. It’s a kind of temp table in the sql query.  One use of this feature is to break down complex query into similar parts. The below is a simple example for with in querying.


;with table1 as
(
      select * from MYTable
),
Table2 as
 (
      select * from MyTable2
),
.
.
.
Table10 as
 (
      select * from MyTable99
)

select * from table1
inner join Table2.ID=table1.ID
Left Outer join table1.ID=Table13.ID



In the final select query we can use sum , group by and etc…

The WITH Common Table Expression (CTE) is used for creating temporary resultsets. This functionality indroudeced in SQL SERVER 2005.

                        

Thursday, June 13, 2013

How to Clear SQL Buffer or cache. Error: There is insufficient memory available in the buffer pool in SQL

Some time we had issues like There is insufficient memory available in the buffer pool in SQL. In the SQL every query, stored procedure and Views will create cache in the sql server memory. This will help our query performance to get the result quickly. Some time the buffer will full in the memory. That time we need to clear the buffer cache. You can clear the buffer cache fully using below query in the SQL new query window.

Clearing SQL Buffer: run below query

DBCC FREEPROCCACHE
DBCC DROPCLEANBUFFER


DBCC FREEPROCCACHE -- Delete or flush modified data to the disk
DBCC DROPCLEANBUFFER -- Remove all deleted and other unwanted sources


If you want to clear particular SP or views query please use below plan handle property to customize the clearing process.

DBCC FREEPROCCACHE (plan_handle | sql_handle | pool_name)

Note:
Please don’t try first in production server. Try in the dev server.

According to MSDN:

Use DBCC FREEPROCCACHE to clear the procedure cache. Freeing the procedure cache would cause, for example, an ad-hoc SQL statement to be recompiled rather than reused from the cache.


Use DBCC DROPCLEANBUFFERS to test queries with a cold buffer cache without shutting down and restarting the server.

Wednesday, June 12, 2013

How to check views tables SP exists in sql server or not ?

Some times in the sql we need to run many scripts at once. Some developers will select particular (create,alter, drop queries one by one) script and run it. This is not a good idea .So while developing the DB script the developer need to maintain the script file as a single file and the single file must check the the schema's already exist or not, if exist no need to run some time. Some time you need to run the script to alter previous one. For that the below functionality will help you to run script easily at one time effort. It will mostly help you while deploying the


How to check view exist in sql server or not?

In the SQL there are several methods to check the views are available or not. The below code is one of the easiest way to check the views information.

First we need to check the views are exist or not. If exist means drop the view and recreate the new one.

Query:

if exists(select count(*) from INFORMATION_SCHEMA.VIEWS where table_name = 'vwMyview' )
BEGIN
drop view vwMyview
END
GO

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE VIEW [dbo].[ vwMyview]
AS
SELECT dbo.ID, dbo.Name FROM  dbo.MyTable

GO




How to check table exist in sql server?

For checking the table exist on not now its very simple code to check that information, We need to pass the table name in the object_id. That object_id  will return the information. Below code is simplest way to get the table exist or not in the sql server.

Query:

IF object_id('LiveData', 'U') is  null
    BEGIN

CREATE TABLE [dbo].[MyTable](
      [Id] [numeric](18, 0) IDENTITY(1,1) NOT NULL,
      [Name] [varchar](50) NULL
)

END



How to check column name exists in sql server or not?

The latest SQL server we have a method name COL_LENGTH to get the table column information. The below two line of code is one of the easy way to get the column name exist in the table or not.


Query:

IF COL_LENGTH('MyTable','ColumnName') IS  NULL
 BEGIN
      ALTER TABLE MyTable
      ADD ColumnName int not null default(0)
 END
 GO



How to check stored procedure exist in sql server or not?

The simplest and easy way to check the stored procedure is exists or not using OBJECT_ID. If the stored procedure is exists we need to drop the procedure and recreate the same. Using this we can run multiple stored procedure at one time.

Query:

IF OBJECT_ID('SP_MYProcedure') IS NOT NULL
DROP PROC SP_MYProcedure
GO

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[SP_MYProcedure]
@ID varchar(50),
@Name varchar(10)
@Action varchar(50)
AS
BEGIN
       
if (@Action='GetData')
BEGIN
SELECT ID, Name FROM  MyTable WHERE ID=@ID   
END

END


How to run multiple create,alter and drop query in one single execution is to using GO key word we can do that. The Go Key word will split the query and its will execute one by one.

Example:

SELECT * from MYTABLE
GO
DROP TABLE MYTABLE
GO
CREATE MYTABLE………











What is the fast and easy way to convert DataTable to JSON string

About Json:
Json is (Javascript object notation) it key/value pairs. its easy to read , write and human editable format. its light wight and the most widely used format for interchanging data on the Website.

We can convert Datatable or Dataset to JSON string in many ways, the below example is the one of the best function to convert datatable to json string. Just pass your datatable to GetDataTableToJson(Datatable) function, this function will return Json string as a return type.


Code:

       //Convert DataTable to JSON String
public string GetDataTableToJson(DataTable dt)
{
            System.Web.Script.Serialization.JavaScriptSerializer jserializer = new System.Web.Script.Serialization.JavaScriptSerializer();
            List<Dictionary<string, object>> lstrows = new List<Dictionary<string, object>>();
            Dictionary<string, object> rowvalue;
            foreach (DataRow dr in dt.Rows)
            {
                rowvalue = new Dictionary<string, object>();
                foreach (DataColumn col in dt.Columns)
                {
                    rowvalue.Add(col.ColumnName, dr[col]);
                }
                lstrows.Add(rowvalue);
            }
            return jserializer.Serialize(lstrows);
        } 





The above method will give you the JONS formatted string as a output. Hope this will help you to use in your project.

Friday, March 29, 2013

Object Oriented Design Principles

Hi This is very good article to understand the OOD Principles. Easy to understand the Interface and Abstract class in C#.

http://www.codeproject.com/Articles/567768/Object-Oriented-Design-Principles


Tuesday, March 12, 2013

SQL SERVER – Stored Procedure Optimization Tips – Best Practices



We will go over how to optimize Stored Procedure with making simple changes in the code. Please note there are many more other tips, which we will cover in future articles.
  • Include SET NOCOUNT ON statement: With every SELECT and DML statement, the SQL server returns a message that indicates the number of affected rows by that statement. This information is mostly helpful in debugging the code, but it is useless after that. By setting SET NOCOUNT ON, we can disable the feature of returning this extra information. For stored procedures that contain several statements or contain Transact-SQL loops, setting SET NOCOUNT to ON can provide a significant performance boost because network traffic is greatly reduced.
-->
CREATE PROC dbo.ProcName
AS
SET
NOCOUNT ON;
--Procedure code here
SELECT column1 FROM dbo.TblTable1
-- Reset SET NOCOUNT to OFF
SET NOCOUNT OFF;
GO
  • Use schema name with object name: The object name is qualified if used with schema name. Schema name should be used with the stored procedure name and with all objects referenced inside the stored procedure. This help in directly finding the complied plan instead of searching the objects in other possible schema before finally deciding to use a cached plan, if available. This process of searching and deciding a schema for an object leads to COMPILE lock on stored procedure and decreases the stored procedure’s performance. Therefore, always refer the objects with qualified name in the stored procedure like
SELECT * FROM dbo.MyTable -- Preferred method
-- Instead of
SELECT * FROM MyTable -- Avoid this method
--And finally call the stored procedure with qualified name like:
EXEC dbo.MyProc -- Preferred method
--Instead of
EXEC MyProc -- Avoid this method
  • Do not use the prefix “sp_” in the stored procedure name: If a stored procedure name begins with “SP_,” then SQL server first searches in the master database and then in the current session database. Searching in the master database causes extra overhead and even a wrong result if another stored procedure with the same name is found in master database.
  • Use IF EXISTS (SELECT 1) instead of (SELECT *): To check the existence of a record in another table, we uses the IF EXISTS clause. The IF EXISTS clause returns True if any value is returned from an internal statement, either a single value “1” or all columns of a record or complete recordset. The output of the internal statement is not used. Hence, to minimize the data for processing and network transferring, we should use “1” in the SELECT clause of an internal statement, as shown below:
IF EXISTS (SELECT 1 FROM sysobjects
WHERE name = 'MyTable' AND type = 'U')
  • Use the sp_executesql stored procedure instead of the EXECUTE statement.
    The sp_executesql stored procedure supports parameters. So, using the sp_executesql stored procedure instead of the EXECUTE statement improve the re-usability of your code. The execution plan of a dynamic statement can be reused only if each and every character, including case, space, comments and parameter, is same for two statements. For example, if we execute the below batch:
DECLARE @Query VARCHAR(100)
DECLARE @Age INT
SET
@Age = 25
SET @Query = 'SELECT * FROM dbo.tblPerson WHERE Age = ' + CONVERT(VARCHAR(3),@Age)
EXEC (@Query)
If we again execute the above batch using different @Age value, then the execution plan for SELECT statement created for @Age =25 would not be reused. However, if we write the above batch as given below,
DECLARE @Query NVARCHAR(100)
SET @Query = N'SELECT * FROM dbo.tblPerson WHERE Age = @Age'
EXECUTE sp_executesql @Query, N'@Age int', @Age = 25
the compiled plan of this SELECT statement will be reused for different value of @Age parameter. The reuse of the existing complied plan will result in improved performance.
  • Try to avoid using SQL Server cursors whenever possible: Cursor uses a lot of resources for overhead processing to maintain current record position in a recordset and this decreases the performance. If we need to process records one-by-one in a loop, then we should use the WHILE clause. Wherever possible, we should replace the cursor-based approach with SET-based approach. Because the SQL Server engine is designed and optimized to perform SET-based operation very fast. Again, please note cursor is also a kind of WHILE Loop.
  • Keep the Transaction as short as possible: The length of transaction affects blocking and deadlocking. Exclusive lock is not released until the end of transaction. In higher isolation level, the shared locks are also aged with transaction. Therefore, lengthy transaction means locks for longer time and locks for longer time turns into blocking. In some cases, blocking also converts into deadlocks. So, for faster execution and less blocking, the transaction should be kept as short as possible.
  • Use TRY-Catch for error handling: Prior to SQL server 2005 version code for error handling, there was a big portion of actual code because an error check statement was written after every t-sql statement. More code always consumes more resources and time. In SQL Server 2005, a new simple way is introduced for the same purpose. The syntax is as follows:
BEGIN TRY
--Your t-sql code goes here
END TRY
BEGIN CATCH
--Your error handling code goes here
END CATCH
Reference: Pinal Dave (http://blog.SQLAuthority.com)

-->