Google Answers Logo
View Question
 
Q: SQL string function ( Answered 5 out of 5 stars,   1 Comment )
Question  
Subject: SQL string function
Category: Computers > Programming
Asked by: vprax-ga
List Price: $3.00
Posted: 09 Aug 2003 16:43 PDT
Expires: 08 Sep 2003 16:43 PDT
Question ID: 241930
I need a T-SQL statement that would parse through a string and look
for a specific character, which is a caret or ^.
There would be four carets in this string and I need to retrieve
anything that is after the third caret and before the fourth caret.
I would also want all spaces trimmed in the result, that is any white
space after the third caret and before the fourth caret should be
trimmed too.
Thanks!
Answer  
Subject: Re: SQL string function
Answered By: cyclometh-ga on 09 Aug 2003 18:53 PDT
Rated:5 out of 5 stars
 
Hello vprax-ga!

I have taken the liberty of answering your question by way of a full
SQL script, which is reproduced below. This was created on MS SQL
Server 2000, and should work on any standard installation of MS SQL
Server 2K. I believe it should also work on SQL Server 7, however I
did not test it in that environment.

The script below performs several operations:

1. Creates a table (CaretStringTable) to contain some data used in the
example.

2. Creates a user-defined function (ParseCaretString), used to process
the strings.

3. Adds several rows of example data to the table.

4. Does a full SELECT * against the table, displaying all rows and the
data in them, so you can compare it against the results desired.

5. Performs a single-statement query which parses the strings within
the SQL statement. As you can see from the comments inline, this is
provided for informational purposes primarily, because it's not a very
efficient mechanism, as it requires the server to do more than it
needs to. However, it does work.

6. Performs the same operation using the ParseCaretString function,
resulting in the same resultset. This is the preferred method, as it
results in a much cleaner set of T-SQL code, and allows for reuse of
the function in other statements.

There are some caveats to this example. First, the function I wrote,
and the SQL code I created for this example may not work properly if
there are fewer than 2 carets (or zero carets) in the string being
parsed. In such cases, spurious results may be returned. You can test
for this by modifying the function body to return the appropriate
results if the string is not formatted as the function expects.

For more information on these functions and how they are put together,
I would recommend searching the Books Online for "string functions" or
"string manipulation functions". For more information on how to create
and use user-defined functions, simply search for "User-Defined
Functions" in the Books online.

	Notes:

There is no "TRIM" function in SQL server, but there is a LTRIM and
RTRIM function, which can be combined as shown to remove both leading
and trailing spaces from a string. The "REVERSE" function is used with
the "LEFT" function to locate the right-most instance of a "^"
character. The same technique is used, with the "RIGHT" function, to
remove the characters preceding the third "^" character.

The "^" character is a wildcard for certain string functions, namely
the "not" expression. However, it only takes on this characteristic if
enclosed in [] characters. Search Books Online for "wildcards" for
more information on this.

	Functions used and a brief description:

RIGHT(expression, numchars): Returns the number of characters
specified in numchars from the right-hand side of a string.

LEFT(expression, numchars): Returns the number of characters specified
in numchars from the left of a string.

REVERSE(expression): Returns the reverse of a string- "the" becomes
"eht". Used in this case to quickly obtain the fourth (last) caret
from a string.

LEN(expression): Returns the number of characters in a string.

LTRIM, RTRIM: Trims leading and trailing whitespace from a string,
respectively.

Beneath the line below you will find a SQL script. Copy and paste it
into Query Analyzer, connected to either the Northwind database, or
any database you are authorized to create objects in, and run the
query. It will return several results to you. It may be necessary to
reformat the script text if Google Answers wraps it inappropriately.

I sincerely hope that this information is of use to you.

Regards,

Cyclometh (cyclometh-ga)

--------------------------------------------

--First, create a table to hold the values we'll be testing.

if exists (select * from dbo.sysobjects where id =
object_id(N'[dbo].[CaretStringTable]') and OBJECTPROPERTY(id,
N'IsUserTable') = 1)
drop table [dbo].[CaretStringTable]
GO

CREATE TABLE [dbo].[CaretStringTable] (
	[ID] [int] IDENTITY (1, 1) NOT NULL ,
	[STRINGTOPARSE] [varchar] (200) COLLATE SQL_Latin1_General_CP1_CI_AS
NULL
) ON [PRIMARY]
GO

--Next, create a function to parse the strings.
if exists (select * from dbo.sysobjects where id =
object_id(N'[dbo].[ParseCaretString]') and xtype in (N'FN', N'IF',
N'TF'))
drop function [dbo].[ParseCaretString]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

CREATE FUNCTION ParseCaretString(@parsestring AS NVARCHAR(200))
RETURNS VARCHAR(200)

AS

BEGIN
--A temporary string variable to hold the string
--as it is being manipulated.
declare @tmpstr varchar(200)

SET @tmpstr=left(@parsestring, len(@parsestring)-charindex('^',
reverse(@parsestring)))
RETURN ltrim(rtrim(right(@tmpstr, charindex('^',
reverse(@tmpstr))-1)))
END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

--Insert some test values into the table.
INSERT INTO CaretStringTable
(STRINGTOPARSE)
VALUES
('a ^test ^^ this is the text ^')

INSERT INTO CaretStringTable
(STRINGTOPARSE)
VALUES
('this ^ is ^ some ^ other text.  ^ some trailing text to be
ignored.')

INSERT INTO CaretStringTable
(STRINGTOPARSE)
VALUES
('and a ^ third string ^^ this text will be displayed.^ this text will
not.')

--Do a full select against the test table, showing all the text
including carets.
select * from caretstringtable

--Directly select the values in question, in one statement.
--This is NOT a very efficient mechanism, but does work. It has to do
a lot of string
--manipulation, in particular performing the LEFT() operation twice,
because we aren't
--using a variable to store the result. This is provided for
educational purposes,
--to show that you can do this in one SQL statement. However, this is
extremely
--inefficient.
select LTRIM(RTRIM(right(left(STRINGTOPARSE,
len(STRINGTOPARSE)-charindex('^', reverse(STRINGTOPARSE))),
	charindex('^', reverse(left(STRINGTOPARSE,
len(STRINGTOPARSE)-charindex('^', reverse(STRINGTOPARSE))-1))))))
FROM caretstringtable

--Do the same as above, except call the function we declared above.
--Using a custom function is much more efficient than doing the
operation
--above, as the string manipulation functions must only be called
once. This
--also results in a much cleaner SQL statement, as you can see.
SELECT dbo.ParseCaretString(STRINGTOPARSE) from caretstringtable
vprax-ga rated this answer:5 out of 5 stars and gave an additional tip of: $2.00
Awesome. Extremely descriptive and clear answer.  If I owned Google, I
would have given a 100 stars!! If I were rich, I would have tipped a
thousand bucks!! But for now, here are two bucks (at least you can get
a gallon of gas on me):-)

Comments  
Subject: Re: SQL string function
From: cyclometh-ga on 26 Aug 2003 22:53 PDT
 
Thank you very much for both the rating and the tip; they're sincerely
appreciated. I'm glad I was able to help, and thanks for using Google
Answers. :)

cyclometh-ga

Important Disclaimer: Answers and comments provided on Google Answers are general information, and are not intended to substitute for informed professional medical, psychiatric, psychological, tax, legal, investment, accounting, or other professional advice. Google does not endorse, and expressly disclaims liability for any product, manufacturer, distributor, service or service provider mentioned or any opinion expressed in answers or comments. Please read carefully the Google Answers Terms of Service.

If you feel that you have found inappropriate content, please let us know by emailing us at answers-support@google.com with the question ID listed above. Thank you.
Search Google Answers for
Google Answers  


Google Home - Answers FAQ - Terms of Service - Privacy Policy