Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations wOOdy-Soft on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Easy Question (I Think)!

Status
Not open for further replies.

GDX

Programmer
Jun 4, 2000
186
US
I am trying to create a function in SQL that will return the position number of a pattern in a string but im not too good with SQL can someone help me? I called it Instr because i have a client that requires me to use this function...

CREATE FUNCTION INstr (@srch varchar,@data varchar)
RETURNS varchar
AS
BEGIN
return (PATINDEX ('%@srch%',@data))
GO

Note: @srch is the pattern its searching for and @data is the whole string, Thank you! Gordon R. Durgha
gd@vslink.net
 
Well, a couple of things show right off the bat:

- PatIndex returns an Int but you're returing a Varchar.

- PatIndex('%@srch%', ...) is going to literally look for "@srch" in what @data evaluates to.
 
Something like this should work:

CREATE FUNCTION INstr (@srch varchar, @data varchar)
RETURNS int
DECLARE @srchme varchar(30)
DECLARE @retcode int
AS
BEGIN
SET @srchme = '%' + @srch + '%'
set @retcode = patindex(@srchme, @data)
return @retcode
END
GO
 
Hi guys the function works now thanks a lot! but now its only returning exact matches not like matches even though i added the %%

ALTER FUNCTION INstr (@srch varchar, @data varchar)
RETURNS int
AS
BEGIN
DECLARE @srchme varchar(30);
DECLARE @retcode int;
SET @srchme = '%' + @srch + '%'
set @retcode = patindex(@srchme, @data)
return @retcode
END
GO

Any Ideas?
Gordon R. Durgha
gd@vslink.net
 
I'm not sure what you mean. If I put this code in SQL Query Analyzer, I get the right result:

DECLARE @srch varchar(30)
DECLARE @data varchar(30)
DECLARE @srchme varchar(30)
DECLARE @retcode int

SET @srch = 'ABC'
SET @data = 'DEFDJABCDJDJ'
SET @srchme = '%' + @srch + '%'
set @retcode = patindex(@srchme, @data)
print @retcode

6
 
Gordon,

Are you using MS SQL or Oracle SQL????? I saw on one of your other posts that you said it was Oracle. If you are using Oracle, it's possible some of the commands, etc posted in this forum won't work for you. If it is Oracle, try the Oracle forums. If you are using the Microsoft SQL then just ignore my comments.

-Bill
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top