Total Pageviews

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

Saturday, November 14, 2009

Ten Common SQL Programming Mistakes

Without further ado, here is the list:
  1. NULLs and the NOT IN predicate
  2. Functions on indexed columns in predicates
  3. Incorrect subquery column
  4. Data type mismatch in predicates
  5. Predicate evaluation order
  6. Outer joins and placement of predicates
  7. Subqueries that return more than one value
  8. Use of SELECT *
  9. Scalar user-defined functions
  10. Overuse of cursors
The examples are presented using SQL Server's Transact-SQL dialect, but most of the concepts are valid in any SQL implementation.


Read full article here
--
Happy Programming

Friday, November 13, 2009

How to Get the Record Count of SQLDataSource?

To get the Record Count or Row Count returned by SQLDataSource control, we have to use DataSourceSelectArgument class.

Create an object to the DataSourceSelectArgument class, set its RetrieveTotalRowCount property to true and by using a DataView we can retrieve the Row Count of the SQLDataSource object. The sample block of code is given below. Try it.


<pre name="code" class="CSharp">

DataSourceSelectArguments dssa = new DataSourceSelectArguments();
dssa.AddSupportedCapabilities(DataSourceCapabilities.RetrieveTotalRowCount);
dssa.RetrieveTotalRowCount = true;
DataView dv = (DataView)SqlDataSource1.Select(dssa);
Response.Write("No of Records : " + dv.Table.Rows.Count);

</pre>

--
happy programming 

Thursday, November 12, 2009

Use Output clause in Delete Statement in sqlserver 2005

Here i give simple example of delete statement with output clause.
if you want track the deleted row information at that time generally
we preffered trigger right?
here we inserte the deleted row in the other history table. we create
the two talbe one is data table and other for history purpose.
1) Create Table (Name:Table_1)
GO
CREATE TABLE [dbo].[Table_1]

( [id] [int] IDENTITY(1,1) NOT NULL,
[code] [varchar](50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,

CONSTRAINT [PK_Table_1] PRIMARY KEY CLUSTERED ( [id] ASC )WITH (IGNORE_DUP_KEY = OFF) ON [PRIMARY] ) ON [PRIMARY]

2) Create Table For Save Deleted Record in other table (DeletedTblInfo)
GO
CREATE TABLE [dbo].[DeletedTblInfo]
( [DeletedTableInfoId] [int] IDENTITY(1,1) NOT NULL,

[DeletedTableId] [int] NULL,
[DeletedRowId] [int] NULL,
 [DeletedDateTime] [datetime] NULL,
CONSTRAINT [PK_DeletedTblInfo] PRIMARY KEY CLUSTERED ( [DeletedTableInfoId] ASC )WITH (IGNORE_DUP_KEY = OFF) ON [PRIMARY] ) ON [PRIMARY]

3) insert data into data table
go
INSERT INTO Table_1
 (code)
VALUES
(‘test1′)

 go
INSERT INTO Table_1
 (code)
 VALUES
(‘test2′)
go

INSERT INTO Table_1
(code)
VALUES
(‘test3′)
go
INSERT INTO Table_1

(code)
VALUES
(‘test4′)
4) now delete from table 1 where id =4
–here the record save in the DeletedTblInfo
–DeletedTableId : the table id where data is deleted or the table name if you want then.
–DeletedRowId : deleted RowId

–DeletedDateTime : deleted DateTime
DELETE FROM Table_1
OUTPUT 1,DELETED.ID,getdate()
INTO DeletedTblInfo WHERE (Id = 4);

–now see the result in the history table
DeletedTableInfoId
DeletedTableId
DeletedRowId
DeletedDateTime
1
1
4
5/7/2008 12:53:52 PM

Thursday, October 29, 2009

EXISTS or COUNT(*) Which Do You Use To Check How Many Rows There Are?

Do you use this

IF (SELECT COUNT(*) FROM SomeTable
WHERE SomeColumn = SomeValue ) > 0

Or do you use this

IF EXISTS (SELECT * FROM SomeTable WHERE SomeColumn = SomeValue )

If you answered COUNT(*) then maybe you should take a look these two articles

Andrew Kelly has a nice post on SQLBlog
http://sqlblog.com/blogs/andrew_kelly/archive/2007/12/15/exists-vs-count-the-battle-never-ends.aspx

Matija Lah has a good post on his snaps & snippets blog
http://milambda.blogspot.com/2006/10/exists-or-not-exists-that-is-question.html

Thursday, October 8, 2009

How do I get the IDENTITY / AUTONUMBER value for the row I inserted?

To get the indentity value of table we can use any of these:

1) INDENT_CURRENT : - IDENT_CURRENT returns the last identity value generated for a specific table in any session and any scope.
 
SELECT IDENT_CURRENT(’tablename’):- It returns the last IDENTITY value produced in a table, regardless of the connection that created the value, and regardless of the scope of the statement that produced the value.IDENT_CURRENT is not limited by scope and session; it is limited to a specified table. IDENT_CURRENT returns the identity value generated for a specific table in any session and any scope.

2) @@IDENTITY :- @@IDENTITY returns the last identity value generated for any table in the current session, across all scopes.
       
SELECT @@IDENTITY :- It returns the last IDENTITY value produced on a connection, regardless of the table that produced the value, and regardless of the scope of the statement that produced the value.@@IDENTITY will return the last identity value entered into a table in your current session. While @@IDENTITY is limited to the current session, it is not limited to the current scope. If you have a trigger on a table that causes an identity to be created in another table, you will get the identity that was created last, even if it was the trigger that created it.



3) SCOPE_IDENTITY :-  SCOPE_IDENTITY returns the last identity value generated for any table in the current session and the current scope.

SELECT SCOPE_IDENTITY() :- It returns the last IDENTITY value produced on a connection and by a statement in the same scope, regardless of the table that produced the value.SCOPE_IDENTITY(), like @@IDENTITY, will return the last identity value created in the current session, but it will also limit it to your current scope as well. In other words, it will return the last identity value that you explicitly created, rather than any identity that was created by a trigger or a user defined function.


Examaple of each:

Create Table #Table
(
    Id int identity(1,1),
    [name] varchar(10)
)
insert into #Table
select 'P'

insert into #Table
select 'S'

insert into #Table
select 'G'

insert into #Table
select 'PP'


select * From #Table

Select  @@Identity As InsertId,IDENT_CURRENT('#Table') As InsertId,SCOPE_IDENTITY() As InsertId

Drop table #Table


------------------------------------------
Note : To avoid the potential problems associated with adding a trigger later on, always use SCOPE_IDENTITY() to return the identity of the recently added row in your T SQL Statement or Stored Procedure.

Friday, September 18, 2009

Bulk Insert From CSV OR Text File In SQL SERVER 2005

One of my friends contacted me recently and said they needed some help creating a stored procedure that imported data from a text file. They wanted the procedure to accept three parameters: PathFileName, ColumnDelimter, and RowDeliter. The PathFileName is simply the name and physical location of the source file on the hard drive, the Delimer are used to identify Columns and rows respectively.
So that i will have give her following store procedure.


Create Proc BulkInsertFromFile
(
@FileName Varchar(500), -- depends on path
@ColumnDelimier Varchar(10), -- delimiter for columns
@RowDelimier Varchar(10)--, -- delimier for Rows  
--@Output varchar(50)  -- used to specify error or success msg
)
As

DECLARE @doesExist INT

SET NOCOUNT ON
EXEC xp_fileexist @FileName, @doesExist OUTPUT
SET NOCOUNT OFF

-- i m creating Temp Table to demonstrate the example
-- Temp table holds the Results copies from FIle

Create Table #Temp
(
[CategoryId] [int],
[UserId] [int] NULL,
[ParentId] [int] NULL,
[CategoryName] [varchar](500),
[Description] [varchar](1000),
[Active] [bit] NULL,
[ImagePath] [varchar](max),
[CreatedDate] [datetime] NULL,
[DeleteStatus] [bit] NULL,
)

IF @doesExist = 1
BEGIN

Declare @SQL  nVarchar(max)  
Declare @Param nVarchar(500)
Set @Param='@FileName Varchar(500),@ColumnDelimier Varchar(20),@RowDelimier Varchar(20)'
SET @SQL = 'BULK INSERT #Temp FROM '''+@FileName+'''
WITH
(
FIELDTERMINATOR ='''+@ColumnDelimier+''',
ROWTERMINATOR ='''+@RowDelimier+''',
FIRE_TRIGGERS
)'

print @SQL
EXEC sp_executesql @SQL,@param,@FileName,@ColumnDelimier,@RowDelimier
--    Set @Output='Bulk insert Completed'
END
--Else
--Begin
--    Set @Output='File does not exist'
--End

---- u can also use the output  param to specify the error msg


Select * From #Temp

Drop table #Temp


Friday, August 7, 2009

SELECT options in SQL

The SQL SELECT statement has the widest variety of query options, which are used to control the way data is returned. These options come in the form of clauses, keywords, and functions.

A clause is a statement that modifies results. Clauses are not required statements, but refine what and how data is displayed. The WHERE clause in a query is one example.

A keyword triggers functionality within the database. These are sometimes required with queries, such as INTO and VALUES in the statement “INSERT INTO table name (column1) VALUES (‘data1’);”. We’ll look at the DISTINCT keyword, which triggers some useful optional functionality.

Functions are built-in statements that apply logic to a result set. We’ll cover several options of this type.

I’ve summarized the most common of these clauses, keywords, and functions below. I’ll explain each one and give examples of usage in the sections that follow.

* ORDER BY—A clause that returns the result set in a sorted order based on specified columns

* DISTINCT—A keyword that returns only unique rows within a result set

* COUNT—A function that returns a numeric value which equals the number of rows matching your query

* AVG—A function that returns the numeric value that equals the average of the numbers in a specified column

* SUM—A function that adds the numbers in a specified column

* MIN—A function that returns the lowest non-null value in a column

* MAX—A function that returns the largest value in a column

* GROUP BY—A clause that summarizes the results of a query function by column

Use ORDER BY to sort results

The ORDER BY clause allows your database to sort your results so that you don’t have to do it “manually” in your application code. The ORDER BY clause must come at the end of a query statement.

Basic usage is as follows:

SELECT * FROM Contacts ORDER BY first_name;

You are free to use ORDER BY with any select statement that might return multiple rows. You can also use it in conjunction with other clauses:

SELECT first_name, last_name FROM Contacts WHERE first_name BETWEEN ‘a’ AND ‘k’ ORDER BY last_name;

You can give multiple columns to sort by. Precedence is given from left to right, so the order in which you list your columns is important.

SELECT * FROM Contacts ORDER BY company, last_name, first_name;

Results are displayed in ascending order by default, either numerically or alphabetically. You can change this behavior by including the DESC keyword following any column name in the ORDER BY clause. In the example below, the highest net_amount will be listed first (in descending order). If two or more rows contain the same net_amount value, they will be displayed showing first the entry with the last_name value that comes earliest in the alphabet, because the last_name column is still sorted in ascending order.

SELECT * FROM Sales ORDER BY net_amount DESC, last_name, first_name;

After running out of defined column names to sort by, most databases will then sort by the first column in the table and work toward the right. Implementation in this area varies though, so if the sort order is important, you should explicitly define which columns to use.

Another handy thing to note is that with the ORDER BY clause (as with the WHERE clause), the columns you are using to sort the results do not have to be part of the returned result set. The following example is perfectly valid, as long as all referenced columns exist in the table:

SELECT company, first_name, net_amount FROM Sales ORDER BY start_date, last_name;

DISTINCT returns unique results

The DISTINCT keyword returns only unique rows within a result set. You may need to find out, for example, which companies are represented in your Sales table, but you don’t want to see every entry. You can use DISTINCT to return one row for each unique company name:

SELECT DISTINCT company FROM Sales;

When you use DISTINCT, it applies to all requested columns. If you want a list of all the salespeople in your table and the companies they represent but not every sales entry, you can use the following statement. Note that this may return several entries from the same company, etc. DISTINCT applies to the entire requested result set.

SELECT DISTINCT company, last_name, first_name FROM Sales;

You can still use DISTINCT when narrowing and sorting your results, as with any SELECT statement. To determine what is displayed, the database first establishes whether the refined request matches a row, then applies the DISTINCT function. The ORDER BY clause is always processed after the entire result set has been determined. In the following example, only rows in which the net_amount is greater than 100 will be returned. Since DISTINCT keeps the first encountered row that matches the query result set and discards the rest, the net_amount column referenced in the ORDER BY statement may seemingly yield randomly ordered results.

SELECT DISTINCT company, last_name, first_name FROM Sales WHERE net_amount > 100 ORDER BY company, net_amount;

Functions apply logic

Functions that return a single value are referred to as aggregate functions. When accessing the results of one of the following aggregate functions from your application, the “field name” containing the results will be the actual function you used. For example, when parsing your database results, the key in your results array may look like one of the following:

$keyname = “COUNT(*)”;

$resultkey = “AVG(net_amount)”;

COUNT

The COUNT function tells you how many rows are in a result set. As with all functions, it accepts one parameter. This basic example will tell you how many rows are in your table:

SELECT COUNT(*) FROM Sales;

You can also use it to count the number of rows in any result set.

SELECT COUNT(*) FROM Sales WHERE net_amount > 100;

If you want to see how many rows contain non-null values for a particular column, you can use COUNT on that column. Note that this will return the total number of rows unless the database is configured to default to NULL when a field is empty for the column in question. Also, listing more than one column name will cause an error.

SELECT COUNT(company) FROM Sales;

COUNT can also be applied to count the number of rows in a DISTINCT result set.

SELECT COUNT(DISTINCT company, last_name) FROM Sales;

The COUNT statement is frequently used to determine the number of iterations to use for a FOR loop in your code.

AVG

AVG returns the average of all the fields in a column with a numeric data type. It accepts one column name as its parameter, and it will return “0” if it's used on a non-numeric column.

SELECT AVG(net_amount) FROM Sales;

You can limit the scope of this function with clauses.

SELECT AVG(net_amount) FROM Sales WHERE company LIKE ‘%ABCD Co%’;

As with all aggregate functions, the ORDER BY statement will be ignored.

SUM

SUM works just like AVG, except it returns the sum of values in all fields in the result set.

SELECT SUM(net_amount) FROM Sales WHERE net_amount > 100;

The AVG, SUM, MIN, and MAX functions will return an error if you do not specify a column, so you can't use the ‘*’ wildcard.

MIN

MIN returns the lowest, non-null value in the specified column. If the column is a numeric data type, the result will be the lowest number. If it's a string data type, it will return the value that comes first alphabetically.

SELECT MIN(net_amount) FROM Sales WHERE last_name = “Smith”;

SELECT MIN(last_name) FROM Sales;

MAX

MAX works just like MIN, only it returns the highest non-null value. It too can be used on strings or numbers.

SELECT MAX(net_amount) FROM Sales;

SELECT MAX(company) FROM Sales WHERE net_amount > 100;

The MAX function is sometimes used on columns containing an auto-incremented key field to determine what the next entry’s key ID will be. Unless you’re running a nonpublic database, be wary of using this information to insert the next entry, in case another user beats you to the punch.

GROUP BY makes functions more useful

While all these functions provide helpful information, the GROUP BY clause lets you apply those functions to a subset of the fields in a column. Rather than running a query containing the MAX function once for every company in your Sales table, you can run one query with the GROUP BY clause to get the same results:

SELECT company, MAX(net_amount) FROM Sales GROUP BY company;

This gives you the highest net_amount for each company. You can also use this statement while selecting multiple column names and use multiple columns to group the function results.

The following examples illustrate the various ways this will produce results. First, including the GROUP BY clause lets you specify additional columns to display. However, be aware that this example will return the first last_name value encountered in the group; the SUM(net_amount) displayed will be for the entire company and not just rows matching the last name. This is because we're using only the company field to define our group.

SELECT company, last_name, SUM(net_amount) FROM Sales GROUP BY company;

In the above example, the last_name column provides pretty useless information, but you're allowed to request it in your query because of the functionality in the next example. You can create groups defined by multiple columns. This will produce function results for unique rows in the result set created by the combination of all specified GROUP BY columns:

SELECT company, AVG(net_amount), last_name FROM Sales GROUP BY company, last_name;

The above example provides the average net_amount for each distinct last name in each company. The order in which you list GROUP BY columns controls the sort order of your results, but the actual function value results will be the same.

Another example shows how you can group results without displaying the grouped columns. This is useful, for example, if you want to show the number of sales per person but keep the names anonymous:

SELECT company, COUNT(sale_id) FROM Sales GROUP BY company, last_name;

Limiting queries that use GROUP BY

As you saw above, you can limit the scope of queries that use these concepts with the WHERE clause. The WHERE clause will be evaluated first, then the function applied. This still holds true when using groups.

SELECT company, AVG(net_amount), FROM Sales WHERE net_amount > 100 GROUP BY company;

The above example will apply the AVG function only to rows that qualified under the WHERE restriction. Note that the WHERE clause must precede the GROUP BY clause. You can also limit the result set returned after the groups are evaluated with the HAVING statement.

SELECT company, AVG(net_amount), FROM Sales WHERE last_name BETWEEN ‘a’ AND ‘m’ GROUP BY company HAVING AVG(net_amount) > 500;

The above statement calculates the average net_amount for each company, evaluating only the values for people whose last names meet the criteria, and displaying only the results that are greater than 500.

Friday, July 3, 2009

Fetch Numer/AlphaNumeric value from Varchar table's Field In SQL SERVER

Following function keeps only numeric characters in string and removes all the other
character from the string. This is very handy function.

    Create FUNCTION dbo.GetNumberFromVarcharField
( 
 @string VARCHAR(max) -- varchar field value 
)
RETURNS VARCHAR(max) 
AS 
BEGIN 
DECLARE @IncorrectCharLoc SMALLINT 
SET @IncorrectCharLoc = PATINDEX('%[^0-9]%', @string)

WHILE @IncorrectCharLoc > 0 
BEGIN 
 SET @string = STUFF(@string, @IncorrectCharLoc,1, '') 
 SET @IncorrectCharLoc = PATINDEX('%[^0-9]%', @string) 
END 
SET @string = @string

RETURN @string 
END 

--- test 

SELECT dbo.GetNumberFromVarcharField('sadas????ASDa######10')

Following function keeps only Alphanumeric characters in string and removes all
the other character from the string. This is very handy function too.

    CREATE FUNCTION dbo.GetAlphaNumericString 
( 
 @string VARCHAR(8000) 
) 
RETURNS VARCHAR(8000) 
AS 
BEGIN

DECLARE @IncorrectCharLoc SMALLINT 
SET @IncorrectCharLoc = PATINDEX('%[^0-9A-Za-z]%',@string) 

WHILE @IncorrectCharLoc > 0 
BEGIN 
 SET @string = STUFF(@string, @IncorrectCharLoc,1, '') 
 SET @IncorrectCharLoc = PATINDEX('%[^0-9A-Za-z]%', @string) 
END 
SET @string = @string 

RETURN @string 
END 
GO 

-- Test 
SELECT dbo.GetAlphaNumericString('ABC”_I+{D[]}4|:e;””5,<.F>/?6')

Tuesday, June 30, 2009

Find out the Binary, ASCII and Character of a Given String in SQL Server

When you are storing data inside fields like ‘address’, there are bound to be unusual characters in it which make way due to poor validation rules. A good way to look for them is to convert your string to varbinary.

Here’s the query:

DECLARE @MyAddress varchar(35)
SET @MyAddress = 'CANTB RY EA%T P.O.Box 55343'

DECLARE    @BIN AS VARBINARY(100)
SET    @BIN = convert(varbinary(100),@MyAddress)

SELECT    SUBSTRING(@BIN, Number, 1) AS Binary,
ASCII(SUBSTRING(@BIN, Number, 1)) AS ASCII,
CHAR(ASCII(SUBSTRING(@BIN, Number, 1))) AS Character
FROM    master..spt_values
WHERE    Type = 'p'
AND Number BETWEEN 1 AND DATALENGTH(@BIN)

Thursday, June 25, 2009

How to retrieve the identity value when inserting a record into a Microsoft SQL Server table

A common requirement when inserting a record into a table that contains an identity column is to return the identity value of the newly inserted record. A common mistake is to use @@IDENTITY or IDENT_CURRENT, both of which could return an unexpected value under some circumstances. This document describes a technique to use SCOPE_IDENTITY which does not suffer the drawbacks of the other two methods.

Why @@IDENTITY and IDENT_CURRENT should not be used

Using @@IDENTITY after an insert will return the last-inserted identity value. However, this might be an unexpected value if, for example, the inserted record fires triggers to perform additional inserts. In this case, calling @@IDENTITY immediately after the statement will return the last identity value generated by the triggers.

Using IDENT_CURRENT after an insert will return the last-inserted identity value for a specified table. However, this might be an unexpected value if another insert on the table is performed between the time of the initial insert and the calling of IDENT_CURRENT.

How and why to use SCOPE_IDENTITY

Using SCOPE_IDENTITY avoids the drawbacks of using @@IDENTITY and IDENT_CURRENT.Note however that SCOPE_IDENTITY is only available with Microsoft SQL Server 2000 or later.The technique for using SCOPE_IDENTITY is to call it immediately after the INSERT statement within a stored procedure. The following example shows a stored procedure called InsertCases that uses this technique to return the identity value for the CaseID identity column of the inserted record. This example has two columns, in addition to the CaseID identity column, called CaseName and CaseDescription. Notice that the @CaseName and @CaseDescription are input parameters but the @CaseID parameter is an output parameter used to return the identity value on exit from the stored procedure.

CREATE PROCEDURE [dbo].[InsertCases] @CaseID int output, @CaseName nvarchar(255), @CaseDescription ntext AS SET NOCOUNT ON INSERT INTO [dbo].[Cases] ([CaseName],[CaseDescription]) VALUES (@CaseName,@CaseDescription) SET @CaseID=SCOPE_IDENTITY() SET NOCOUNT OFF

The following example shows how to call the InsertCases stored procedure using the Microsoft .NET Framework. Notice that the @CaseID parameter is set as an output parameter by setting its Direction property to arameterDirection.Output which allows it to return the CaseID identity value after the stored procedure has been executed.

C#

Command.Parameters.Add(new System.Data.SqlClient.SqlParameter(”@CaseID”,System.Data.SqlDbType.Int));

Command.ExecuteNonQuery();

CaseID = System.Convert.ToInt32( Command.Parameters["@CaseID"].Value);

Conclusion

By using SCOPE_IDENTITY within a stored procedure, the identity value of the most recently inserted record can always be correctly obtained.

Friday, May 29, 2009

Custom Paging in GridView without Object Data Source

All we need to use the Custom paging in grid view without object data source.

Here i am going to explain my code which is used in custom paging of grid view... What you will need to do is used your DataSource SP or query with this paging...

All magic lies in SQL Server 2005 ROWNumber() Function.... Simple SP for this gridview datasource is


Select Row,ID,Name
(
    Select ROW_Number()OVER(ORDER BY ID) As Row,ID,Name 
    from table1
) AS A
Where Row=>@PageIndex*PageSize
and Row<(@PageIndex+1)*PageSize;
--here @PageIndex and @PageSize are passed as parameter as gridview1.PageIndex and gridview1.PageSize  
    

if you are not familiar with RowNumber function than create one temp table use Row as primary key with auto increament number and than use insert select statement.... this will work in all database.....

Follow is the C# code for custom gridview...I m creating new grid view control here

using System; 
using System.Collections.Generic; 
using System.ComponentModel; 
using System.Text; 
using System.Web; 
using System.Web.UI; 
using System.Web.UI.WebControls;  
namespace CustomPagingGridView 
{  
    [DefaultProperty("Text")]  
    [ToolboxData("<{0}:CustomePagingGrid runat=server>CustomePagingGrid>")]  
    public class CustomePagingGrid : GridView 
    {   
        public CustomePagingGrid(): base()
        {}
        
        #region Custom properties       
        // this property is to use to find the total number of record for grid         
        [Browsable(true), Category("NewDynamic")]         
        [Description("Set the virtual item count for this grid")]         
        public int VirtualItemCount         
        {             
            get
            {
                if (ViewState["pgv_vitemcount"] == null)
                    ViewState["pgv_vitemcount"] = -1;                 
                return Convert.ToInt32(ViewState["pgv_vitemcount"]);             
            }             
            set             
            {                 
                ViewState["pgv_vitemcount"] = value;             
            }         
        }         
        
        // this is used to sort the gridview columns        
        [Browsable(true), Category("NewDynamic")] [Description("Get the order by string to use for this grid when sorting event is triggered")] 
        public string OrderBy         
        {             
            get             
            {                 
                if (ViewState["pgv_orderby"] == null)                     
                    ViewState["pgv_orderby"] = string.Empty;                 
                return ViewState["pgv_orderby"].ToString();             
            }             
            protected set             
            {                 
                ViewState["pgv_orderby"] = value;             
            }         
        }            
        
        private int Index         
        {             
            get             
            {                 
                if (ViewState["pgv_index"] == null)                     
                    ViewState["pgv_index"] = 0;                 
                return Convert.ToInt32(ViewState["pgv_index"]);             
            }             
            set             
            {                 
                ViewState["pgv_index"] = value;             
            }         
        }            
        
        public int CurrentPageIndex         
        {             
            get             
            {                 
                if (ViewState["pgv_pageindex"] == null)                     
                    ViewState["pgv_pageindex"] = 0;                 
                return Convert.ToInt32(ViewState["pgv_pageindex"]);             
            }             
            set             
            {                 
                ViewState["pgv_pageindex"] = value;             
            }         
        }            
        
        private int SetCurrentIndex         
        {             
            get             
            {                 
                return CurrentPageIndex;             
            }             
            set             
            {                 
                CurrentPageIndex = value;             
            }         
        }                 
        
        
        // if this property is set to greater than zero means custom paging neede                    
        private bool CustomPaging         
        {             
            get             
            {                 
                return (VirtualItemCount != -1);             
            }         
        }          
        #endregion             
        
        #region Overriding the parent methods           
        public override object DataSource         
        {             
            get             
            {                 
                return base.DataSource;             
            }             
            set             
            {                 
                base.DataSource = value;                 
                // we store the page index here so we dont lost it in databind                 
                CurrentPageIndex = PageIndex;             
            }         
        }     
        
        protected override void OnSorting(GridViewSortEventArgs e) 
        { 
            // We store the direction for each field so that we can work out whether next sort 
            // should be asc or desc order  PageIndex = CurrentPageIndex; SortDirection direction = SortDirection.Ascending;  
            if(ViewState[e.SortExpression]!=null&& (SortDirection)ViewState[e.SortExpression] == SortDirection.Ascending)  
            {   
                direction = SortDirection.Descending; 
            }  
            ViewState[e.SortExpression] = direction;             
            OrderBy = string.Format("{0} {1}", e.SortExpression, (direction == SortDirection.Descending ? "DESC" : ""));             
            base.OnSorting(e);         
        }            
        
        protected override void InitializePager(GridViewRow row, int columnSpan, PagedDataSource pagedDataSource)         
        {             
            // This method is called to initialise the pager on the grid. We intercepted this and override             
            // the values of pagedDataSource to achieve the custom paging using the default pager supplied             
            if (CustomPaging)             
            {                 
                pagedDataSource.AllowCustomPaging = true;                 
                pagedDataSource.VirtualCount = VirtualItemCount;                 
                pagedDataSource.CurrentPageIndex = CurrentPageIndex;             
            }             
            base.InitializePager(row, columnSpan, pagedDataSource);         
        }               
        
        // here we do custom paging         
        protected override void OnPageIndexChanging(GridViewPageEventArgs e)         
        {             
            if (CustomPaging)             
            {                 
                if (this.PagerSettings.Mode == PagerButtons.NumericFirstLast || this.PagerSettings.Mode == PagerButtons.Numeric)                 
                {                     
                    base.OnPageIndexChanging(e);                 
                }                 
                else                 
                {                     
                    if (e.NewPageIndex == -1)                     
                    {                         
                        Index -= 1;                     
                    }                     
                    else if (e.NewPageIndex == 0)
                    {                         
                        Index = 0;                     
                    }                     
                    else if (e.NewPageIndex == ((int)Math.Ceiling((decimal)(VirtualItemCount) / PageSize) - 1))                     
                    {                         
                        Index = ((int)Math.Ceiling((decimal)(VirtualItemCount) / PageSize) - 1);                     
                    }                     
                    else                     
                    {                         
                        Index += 1;                     
                    }                     
                    if (Index < 0)                     
                    { 
                        Index = 0; 
                    }
                    CurrentPageIndex = Index;                     
                    e.NewPageIndex = Index;                     
                    base.OnPageIndexChanging(e);                 
                }             
            }         
        }           
    #endregion     
    } 
}
    

if u have any doubt,please feel free to ask me....

Wednesday, April 22, 2009

Get Primary key - Foreign key relations table in sql server 2005

Get Primary key - Foreign key relations table in sql server 2005 Why it is required? The main purpose of this is finding related constraint table from database. Check below Query....


--get table list with constraint(primary and foreign key)  

select * from information_schema.constraint_column_usage  

--get table list with foreign key constraint  
select * from information_schema.referential_constraints  

--get the relation  
select tblAll.table_name as PrimaryTableName, tblAll.column_name as PrimaryTableColumn, 
tblFK.table_name as ForeignKeyTable, tblFK.column_name as ForeignKeyColumn 
from information_schema.constraint_column_usage tblAll 
inner join information_schema.referential_constraints tblAllFK on tblAllFK.unique_constraint_name = tblAll.constraint_name 
inner join information_schema.constraint_column_usage tblFK on tblAllFK.constraint_name=tblFK.constraint_name   

thnx

Thursday, April 16, 2009

Regular Expression in Sqlserver 2005


Regular Expression in Sqlserver 2005.

why Regular Expression Required for sqlserver 2005? The basic need Of Regular Expression
is avoiding hard work for searching or pattern maching in database. Example if i
want to search valid email address from users table then what will be senario for
that? i have thousand of newly registered user daily. then how to i find invalid
Email Address from that? let’s start with regular expression in sqlserver 2005.
the basic requirement for that configure OLE Object in to Server. –Configure OLE
Automation object. –EXECUTE permission set for object ’sp_OACreate’

use[master] GO GRANT EXECUTE ON[sys].[sp_OASetProperty] TO [public] 
GO 
use[master] 
GO 
GRANT EXECUTE ON[sys].[sp_OAMethod] TO[public] 
GO use[master] 
GO GRANT EXECUTE ON[sys].[sp_OAGetErrorInfo] TO[public] 
GO use[master] 
GO GRANT EXECUTE ON[sys].[sp_OADestroy] TO[public] 
GO use[master] 
GO GRANT EXECUTE ON[sys].[sp_OAStop] TO[public] 
GO use[master] 
GO GRANT EXECUTE ON[sys].[sp_OACreate] TO[public] 
GO use[master] 
GO GRANT EXECUTE ON[sys].[sp_OAGetProperty] TO[public] 
GO sp_configure’show advanced options’,1 
GO reconfigure go  execsp_configure go execsp_configure‘Ole Automation Procedures’,
        

1 – Configuration option ‘Ole Automation Procedures’ changed from 0 to 1. Run the
RECONFIGURE statement to install. go reconfigure go steps : 1) Create Scalar Value
Function In Sqlserver 2005.


create FUNCTION dbo.RegEx     
(         
 --Expression Target / Source         
 @Target varchar(5000),         
 --Regular Expression Pattern         
 @Pattern varchar(Max),         
 --whether the expression case sensitive         
 @CaseSensitive bit = 0     
) 
RETURNS bit 
AS     
BEGIN         
DECLARE @ReturnOACreate int         
DECLARE @ObjToken int         
DECLARE @objMatches int         
DECLARE @objMatch int         
DECLARE @count int         
DECLARE @results bit          

EXEC @ReturnOACreate = sp_OACreate 'VBScript.RegExp', @ObjToken OUTPUT          
--objecttoken OUTPUT         
--Is the returned object token, and must be a local variable of data type int.         
--This object token identifies the created OLE object and is used in calls to the other         
--OLE Automation stored procedures.         
--Return         
--0 (success) or a nonzero number (failure) that is the integer value of the         
--HRESULT returned by the OLE Automation object          
IF @ReturnOACreate <> 0 
BEGIN             
    SET @results = 0             
    RETURN @results         
END          
EXEC @ReturnOACreate = sp_OASetProperty @ObjToken, 'Pattern', @Pattern          
IF @ReturnOACreate <> 0 
BEGIN             
    SET @results = 0             
    RETURN @results         
END          
EXEC @ReturnOACreate = sp_OASetProperty @ObjToken, 'Global', false         
IF @ReturnOACreate <> 0 
BEGIN             
    SET @results = 0             
    RETURN @results         
END          
EXEC @ReturnOACreate = sp_OASetProperty @ObjToken, 'IgnoreCase', @CaseSensitive         
IF @ReturnOACreate <> 0 
BEGIN             
    SET @results = 0             
    RETURN @results         
END              
EXEC @ReturnOACreate = sp_OAMethod @ObjToken, 'Test', @results OUTPUT, @Target         
IF @ReturnOACreate <> 0 
BEGIN             
    SET @results = 0             
    RETURN @results         
END          
EXEC @ReturnOACreate = sp_OADestroy @ObjToken         
IF @ReturnOACreate <> 0 
BEGIN             
    SET @results = 0             
    RETURN @results         
END     

--return 1 for success     
RETURN @results     
END          

2) Now use this function for Matching the Expression.


  • case 1: simple regular expression match
            select dbo.RegEx( N'122-45-6789', N'^\d{3}-\d{2}-\d{4}$',0 )      
            run this it return 0 it indicate this expression is valid.  
        
            select dbo.RegEx( N'1224-45-6789', N'^\d{3}-\d{2}-\d{4}$',0 )      
            run this it return 1 it indicate this expression is InValid.  
            

  • case 2: Get the data from Table now the senario is i am finding the valid email address from the table (here i used simple regular expression which is made manual for demo purpose you can use any of them.)
        declare @tblTmp as table(id int identity(1,1),emailaddress varchar(50))  
        insert into @tblTmp values ('test@yahoo') 
        insert into  @tblTmp values ('test@gmail.test') 
        insert into @tblTmp values ('t@gmail.com') 
        insert into @tblTmp values ('test@test.com') 
        insert into  @tblTmp values ('test@test.')  
        
        select * from @tblTmp  
        --find valid email address 
        
        select * from @tblTmp where dbo.RegEx(emailaddress,'^[A-Za-z0-9._%-]+@[a-zA-Z0-9]+\.[a-zA-Z]{2,4}$',0)=1
        

Wednesday, April 15, 2009

Split Function in SQL Server

Sql Server does not (on my knowledge) have in-build Split function. Split function
in general on all platforms would have comma-separated string value to be split
into individual strings. In sql server, the main objective or necessary of the Split
function is to convert a comma-separated string value (‘abc,cde,fgh’) into a temp
table with each string as rows.

The below Split function is Table-valued function which would help us splitting
comma-separated (or any other delimiter value) string to individual string.

Create FUNCTION [dbo].[Split]
( 
 @String varchar(8000), @Delimiter char(1)
)
returns @temptable TABLE (items varchar(8000)) 
as 
begin 

declare @idx int 
declare @slice varchar(8000) 

select @idx = 1 

if len(@String)<1 or @String is null 
 return 

while @idx!= 0 
begin 
 
 set @idx = charindex(@Delimiter,@String)  
 if @idx!=0 
  set @slice =left(@String,@idx - 1) 
 else 
  set @slice = @String 

 if(len(@slice)>0) 
  insert into @temptable(Items)values(@slice) 

 set @String = right(@String,len(@String) - @idx) 
 if len(@String)= 0 
 break 
end 
return 
end 

--now fire this query 
select top 10 * from dbo.split('Chennai,Bangalore,Mumbai',',')

--this will return following results. 
-- Items -----------------------
--Chennai 
--Bangalore 
--Mumbai

Tuesday, April 14, 2009

SQL Native Client (SQLNCLI )

SQl server uses a new database provider model. This provider succeeds OLEDB. OLEDB
was used for SQL Server databases. Now even it's possible to access MS Access databases
that way. ODBC is only for backward compatability. The new SQLNCLI provider has
the following new features

  • - Support for the new SLQ 2005 large datatypes (Max String, with no limited length)
  • - XML Datatype (Not just a handle, but a real type)
  • - Custom Datatypes (UDT)
  • - The new snapshot isolation level.This level does not lock dirty reads. It uses
    optimistic (locking). It's the best of both worlds. Enabled to read all actual committed
    data, skipping locks, but reading the data (dirty reads),and persisting data if
    the data is not locked.
  • - Supprot for multiple active recordsets. It was already possible to get multiple
    recordsets. In Ado.Net, with movenext, the next result could be read. But now, it's
    possible to have multiple connections open. So each recordset (multiple retrieval)
    can have it's own connection.
  • - Password can be changed at the client, without the need of the administrator.
  • - Support for asynchoon operations. Lots of complex database actions take a time.
    Now SQL server can create threads to do jobs on its own.
  • - It supports SQLXML 4.0. The new connection string (just another provider) "Provider=SQLNCLI;Server=(local);Database=Northwind;IntegratedSecurity=SSPI;" For DSN connections (who uses them still?) "Driver={SQL Native Client}; Server=(local); Database=Northwind; Trusted_Connection=yes;"

Blog Archive

Ideal SQL Query For Handling Error & Transcation in MS SQL

BEGIN TRY BEGIN TRAN --put queries here COMMIT; END TRY BEGIN CATCH IF @@TRANCOUNT>0 BEGIN SELECT @@ERROR,ERRO...