Quick Search for:  in language:    
   Code/Articles ╗ |  Newest/Best ╗ |  Community ╗ |  Jobs ╗ |  Other ╗ |  Goto ╗ | 
CategoriesSearch Newest CodeCoding ContestCode of the DayAsk A ProJobsUpload
SQL Stats

 Code: 45,316. lines
 Jobs: 126. postings

 How to support the site

Sponsored by:

You are in:

Latest Code Ticker for SQL.
sp_db_paging_pr imary_key
By Marcus LeBlanc on 1/11

By Marcus LeBlanc on 1/11

Beginners pack
By hardik shah on 1/11

Inline Views
By Thivya Prabakaran on 1/6

Click here to put this ticker on your site!

Add this ticker to your desktop!

Daily Code Email
To join the 'Code of the Day' Mailing List click here!

Affiliate Sites


Sorting a String using T-SQL

VB icon
Submitted on: 10/12/2002 6:56:52 AM
By: Gaurav Pugalia 
Level: Intermediate
User Rating: By 2 Users
Compatibility:SQL Server 2000

Users have accessed this code 2643 times.
(About the author)
     This is a User Defined Function in T-SQL for MSSQL Sevre 2000 which sorts the input string, and returns it to the caller. Optinals include sort direction (ascending/descending), sort preference(lower case / upper case preference), sort type (case sensitive / insensitive).
Can't Copy and Paste this?
Click here for a copy-and-paste friendly version of this code!
Terms of Agreement:   
By using this code, you agree to the following terms...   
1) You may use this code in your own programs (and may compile it into a program and distribute it in compiled format for languages that allow it) freely and with no charge.   
2) You MAY NOT redistribute this code (for example to a web site) without written permission from the original author. Failure to do so is a violation of copyright laws.   
3) You may link to this code from another website, but ONLY if it is not wrapped in a frame. 
4) You will abide by any additional copyright restrictions which the author may have placed in the code or code's description.

-- Name: Sorting a String using T-SQL
-- Description:This is a User Defined Fu
--     nction in T-SQL for MSSQL Sevre 2000 whi
--     ch sorts the input string, and returns i
--     t to the caller. Optinals include sort d
--     irection (ascending/descending), sort pr
--     eference(lower case / upper case prefere
--     nce), sort type (case sensitive / insens
--     itive).
-- By: Gaurav Pugalia
-- Inputs:Parameters: 4				
@inStr : input string TO be sorted,
@sortDirection : Ascending or Descending
@sortType: CASE Insensitive or sensitive 
@preference : Lower OR Upper CASE preference.
-- Returns:Sorted string as per specifie
--     d preferences
-- Assumes:Transact-SQL
-- Side Effects:Tell me about 'em !
--This code is copyrighted and has-- limited warranties.Please see http://
--     www.Planet-Source-Code.com/vb/scripts/Sh
--     owCode.asp?txtCodeId=568&lngWId;=5--for details.--**************************************

CREATE FUNCTION funcStrSort (@inStr varchar(8000), @sortDirection char,
 @sortType char, @preference char)
RETURNS varchar(8000)
/************************* funcStrSort **********************************************************************
Written By: Gaurav Pugalia																				*
Date : October 07, 2002																			*
Description	 : This UDF sorts the input string 															*
Compatibility : MSSQL Server 2000																			*
Parameters : 4																							*
@inStr : input string TO be sorted, upto 8000 characters											*
 (since MSSQL varchar fields are limited TO 8000 characters)								*
@sortDirection : Ascending(default) or Descending(use 'd' or 'D' TO specify descending sort)				*
@sortType : CASE Insensitive(default) or Sensitive(use 'S' or 's' TO specify a sensitive sort)			*
@preference: Lower OR Upper CASE preference. DEFAULT IS the collating sequence (assuming ASCII). 		*
				 Specify a 'l' OR 'L' TO specify lower CASE preference), ignored if insensitive search *
RETURN Value: Sorted string AS per specified preferences													*
    BEGIN -- begin function
    DECLARE @len smallint, @i smallint, @j smallint
    DECLARE @char1 char, @char2 char
    SET @len = LEN(@inStr)
    SET @i = 1
    WHILE @i <= @len-1
        BEGIN-- begin major loop
        	SET @j = @i + 1
        	WHILE @j <= @len
        	BEGIN			-- begin minor loop
        		SET @char1 = SUBSTRING(@inStr,@i,1)
        		SET @char2 = SUBSTRING(@inStr,@j,1)
        		IF @sortType IS NULL OR @sortType = '' OR UPPER(@sortType) <> 'S'
        			IF @char2 < @char1
        	 		 SET @inStr =
        LEFT(@inStr,@i-1) + @char2 + SUBSTRING(@inStr,@i+1,@j-@i-1) + @char1 + RIGHT(@inStr,@len-@j)
        			IF ASCII(@char2) < ASCII(@char1)
        	 		 SET @inStr =
        LEFT(@inStr,@i-1) + @char2 + SUBSTRING(@inStr,@i+1,@j-@i-1) + @char1 + RIGHT(@inStr,@len-@j)
        	SET @j = @j + 1 -- increment minor loop counter
        	END				-- end minor loop
        SET @i = @i + 1 -- increment major loop counter
    END				-- end major loop

/* IF sensitive sort AND lower CASE prefernce, do the needful */ IF UPPER(@sortType) = 'S' AND UPPER(@preference) = 'L' BEGIN SET @i = @len WHILE @i > 0 AND ( ASCII(SUBSTRING(@inStr,@i,1)) BETWEEN ASCII('a') AND ASCII('z') ) BEGIN SET @i = @i-1 END SET @inStr = RIGHT(@inStr,@len-@i) + LEFT(@inStr,@i) END
/* IF want a descending sort, reverse the string */ IF UPPER(@sortDirection) = 'D' BEGIN SET @inStr = REVERSE(@inStr) END
RETURN @inStr-- return the sorted string END -- end function

Other 1 submission(s) by this author


Report Bad Submission
Use this form to notify us if this entry should be deleted (i.e contains no code, is a virus, etc.).
Your Vote!

What do you think of this code(in the Intermediate category)?
(The code with your highest vote will win this month's coding contest!)
Excellent  Good  Average  Below Average  Poor See Voting Log
Other User Comments
10/24/2002 12:01:53 PM:Rajesh Patel
This is poor documentation. He says 
some of the arguments are default. But, 
if we don't sepcify argument. function 
returns an error 'argument missing'. 
Default values means you don't need to 
pass that argument, if you want to use 
Keep the Planet clean! If this comment was disrespectful, please report it:

Add Your Feedback!
Note:Not only will your feedback be posted, but an email will be sent to the code's author in your name.

NOTICE: The author of this code has been kind enough to share it with you.  If you have a criticism, please state it politely or it will be deleted.

For feedback not related to this particular code, please click here.


Categories | Articles and Tutorials | Advanced Search | Recommended Reading | Upload | Newest Code | Code of the Month | Code of the Day | All Time Hall of Fame | Coding Contest | Search for a job | Post a Job | Ask a Pro Discussion Forum | Live Chat | Feedback | Customize | SQL Home | Site Home | Other Sites | About the Site | Feedback | Link to the Site | Awards | Advertising | Privacy

Copyrightę 1997 by Exhedra Solutions, Inc. All Rights Reserved.  By using this site you agree to its Terms and Conditions.  Planet Source Code (tm) and the phrase "Dream It. Code It" (tm) are trademarks of Exhedra Solutions, Inc.