Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 General SQL Server Forums
 New to SQL Server Programming
 f i n d i n g n th

Author  Topic 

aakcse
Aged Yak Warrior

570 Posts

Posted - 2009-07-29 : 10:20:24
hi all,

I need to find the n th occurance in the string say for eg.

('abc\xyz\total\endreport)

from the above if i want to find a 2nd occurance or say 3rd occurance of \ in this can any one help me with this.

Regard,
aak

X002548
Not Just a Number

15586 Posts

Posted - 2009-07-29 : 10:25:28
What do you mean by find?

The Offset position of a value in a string?





Brett

8-)

Hint: Want your questions answered fast? Follow the direction in this link
http://weblogs.sqlteam.com/brettk/archive/2005/05/25/5276.aspx

Add yourself!
http://www.frappr.com/sqlteam



Go to Top of Page

aakcse
Aged Yak Warrior

570 Posts

Posted - 2009-07-29 : 10:32:52
yes The Offset position of a value in a string.

Thanks
Go to Top of Page

X002548
Not Just a Number

15586 Posts

Posted - 2009-07-29 : 10:34:14
You can modify this



CREATE FUNCTION [dbo].[udf_LAST_SPACE]
(@str varchar(8000))
RETURNS int
AS
BEGIN
DECLARE @Words INT, @Pos INT, @x Int, @y Int
SELECT @Words = 0, @Pos = 1, @x = -1

WHILE (@x <> 0)
BEGIN
SET @y = @x
SET @x = CHARINDEX(' ', @str, @Pos)
SET @Pos = @x + 1
SET @Words = @Words + 1
END

RETURN @y
END




Brett

8-)

Hint: Want your questions answered fast? Follow the direction in this link
http://weblogs.sqlteam.com/brettk/archive/2005/05/25/5276.aspx

Add yourself!
http://www.frappr.com/sqlteam



Go to Top of Page

X002548
Not Just a Number

15586 Posts

Posted - 2009-07-29 : 11:06:28
Here...this does it


USE [dba]
GO

IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[udf_FIND_OFFSET]') AND type in (N'FN', N'IF', N'TF', N'FS', N'FT'))
DROP FUNCTION [dbo].[udf_FIND_OFFSET]
GO

CREATE FUNCTION [dbo].[udf_FIND_OFFSET]
(@str varchar(8000),@target varchar(8000),@offset int)
RETURNS int
AS
BEGIN
DECLARE @Words INT, @Pos INT, @x Int, @y Int
SELECT @Words = 0, @Pos = 1, @x = -1

WHILE (@Words <= @offset)
BEGIN
SET @y = @x
SET @x = CHARINDEX(@target, @str, @Pos)
SET @Pos = @x + 1
SET @Words = @Words + 1
END

RETURN @y
END
GO

DECLARE @t table(Col1 varchar(8000))

INSERT INTO @t(Col1)
SELECT 'abc\xyz\total\endreport'

SELECT *, dbo.[udf_FIND_OFFSET](Col1,'\',2) FROM @t
GO





Brett

8-)

Hint: Want your questions answered fast? Follow the direction in this link
http://weblogs.sqlteam.com/brettk/archive/2005/05/25/5276.aspx

Add yourself!
http://www.frappr.com/sqlteam



Go to Top of Page
   

- Advertisement -