SQL Server SUBSTRING - Explained

Pandians
Posted by in Sql Server category on for Beginner level | Views : 63387 red flag
Rating: 5 out of 5  
 1 vote(s)

We have used SUBSTRING in many ways/scenarios. This article explains how it works.
Introduction
We use SUBSTRING function in SQL Server many ways/scenarios to return some part of string.

Scenarios
I just want to return some part of string from the string given below

Syntax
SUBSTRING
(expression,start,length)

DECLARE @SampleString VARCHAR(11)
SELECT
@SampleString = 'Dotnetfunda'

SELECT
SUBSTRING(@SampleString,1,1)
D

SELECT
SUBSTRING(@SampleString,1,2)
Do

SELECT
SUBSTRING(@SampleString,1,0)
<
BLANK>

SELECT
SUBSTRING(@SampleString,0,1)
<BLANK>


SELECT
SUBSTRING(@SampleString,-1,3)
D

SELECT
SUBSTRING(@SampleString,-1,0)
<
BLANK>

SELECT
SUBSTRING(@SampleString,-10,12)
D

SELECT
SUBSTRING(@SampleString,-11,23)
Dotnetfunda

How it Works
start + length - 1 = Number of String



SELECT SUBSTRING(@SampleString,-11,22)
Start   = -11
Length = 22
Result is : (-11 + 22) - 1   =   10, So that it returns 10 Chanacters : Dotnetfund


 
Page copy protected against web site content infringement by Copyscape

About the Author

Pandians
Full Name: Pandian Sathappan
Member Level: Silver
Member Status: Member,MVP
Member Since: 5/11/2009 2:24:28 AM
Country: India
Cheers www.SQLServerbuddy.blogspot.com iLink Multitech Solutions
http://sqlserverbuddy.blogspot.com/
Microsoft Certification - MCITP: Microsoft Certified IT Professional - SQL Server 2008 Database Administrator - MCTS: Microsoft Certified Technology Specialist - SQL Server 2005 - MCP: Microsoft Certified Professional - SQL Server 2000

Login to vote for this post.

Comments or Responses

Login to post response

Comment using Facebook(Author doesn't get notification)