SQL Server - Selecting SUBSTRING from a string using LastIndexOf in Sql Server

Asked By Kishore Rajendran
17-May-11 05:30 AM
Hi, can anyone point me to a function in MSSQL that returns the last index of a character in a string? I'm trying to find the base filename from a field that returns the full path.
 
Eg. if db contained rows:
C:\temp\file1.bat
C:\temp\Aug10\file2.bat
 
I would want as result:
file1.bat
file2.bat
 

The only solution I've come up with so far is to create a temporary table with the filenames, and recurse using update statements on the table until there are no more updates. There has to be a better solution.
  Ravi S replied to Kishore Rajendran
17-May-11 05:32 AM
HI

refer this example

public class MainClass
{
   public static void mainString args[] )
   {
    String letters = "abcdefghijklmabcdefghijklm";

    System.out.printf"Last \"def\" is located at index %d\n",
      letters.lastIndexOf"def" ) );
     System.out.printf"Last \"def\" is located at index %d\n",
      letters.lastIndexOf"def"25 ) );
     System.out.printf"Last \"hello\" is located at index %d\n",
      letters.lastIndexOf"hello" ) );
   }
}

refer the link also
http://www.java2s.com/Tutorial/Java/0040__Data-Type/UselastIndexOftofindasubstringinastring.htm
  Ravi S replied to Kishore Rajendran
17-May-11 05:36 AM
Hi

refer this link
http://msdn.microsoft.com/en-us/library/ms187748.aspx
  James H replied to Kishore Rajendran
17-May-11 05:39 AM

Hi,

T-sql developers can find sql codes for extracting file name from fullpath of a file.

No matter whether the file path is stored in a sql table column or full filepath is supplied as a sql variable or sql string parameter, sql developers can use either sql functions to parse file name or use sql string functions in order to extract file name.

Here is sample t-sql code that sql developers can use to extract filename from path given as sql string variable or extract filename from path stored in sql table column.
In this SQL SELECT statement, sql string functions like CHARINDEXSUBSTRING and REVERSEfunctions are used.

Let's create a sample sql database table and insert sample records for the sql sample to extract file name from file path.

Create Table FileSystem (
  FileID int identity(1,1),
  FullFilePath nvarchar(1000)
)
 
INSERT INTO FileSystem VALUES (
 N'D:\SQLDatabases\SQLSampleDatabase.mdf'
);
INSERT INTO FileSystem VALUES (
 N'C:\Program Files\Microsoft SQL Server\100\Samples\License.rtf'
);

Here is the sample sql codes which works on the above sql sample data and parse filename from full filepath.

SELECT
 LTRIM(
  RTRIM(
   REVERSE(
  SUBSTRING(
   REVERSE(FullFilePath),
   0,
   CHARINDEX('\', REVERSE(FullFilePath),0)
  )
   )
  )
 )
FROM FileSystem

And the output of the above sql script which sql parse file path string value for file name is as follows.

t-sql-parse-file-name-from-file-path


Here is user function source code of sample sql functions to extract file name from path.
ALTER FUNCTION GetFileName
(
 @fullpath nvarchar(max),
 @delimiter nvarchar(100)
) RETURNS nvarchar(max)
AS
BEGIN
 
declare @split as table (
 id int identity(1,1),
 fragment nvarchar(max)
)
declare @filename nvarchar(max)
declare @xml xml
 
SET @xml =
 N'<root><r>' +
 REPLACE(@fullpath, @delimiter,'</r><r>') +
 '</r></root>'
 
INSERT INTO @split(fragment)
SELECT
 r.value('.','nvarchar(max)') as item
FROM @xml.nodes('//root/r') as records(r)
 
SELECT @filename = fragment
FROM @split
WHERE id = (SELECT MAX(id) FROM @split)
 
RETURN LTRIM(RTRIM(@filename))
 
END

Here is a sample sql function call which parse file name from a given file path and returns the file name to the sql user.

SELECT dbo.GetFileName(N'C:\SQLDatabases\SQLBackup.mdf',N'\') as [File Name]

And the above sample function call code returns the "SQLBackup.mdf" as the output for the SELECT statement.

  TSN ... replied to Kishore Rajendran
17-May-11 05:42 AM
hi..

You can Use Substring Keyword in the sqlserver which gives your desired result..

SUBSTRING ( value_expression , start_expression , length_expression )
value_expression

Is a character, binary, text, ntext, or image http://msdn.microsoft.com/en-us/library/ms190286.aspx.

start_expression

Is an integer or bigint expression that specifies where the returned characters start. If start_expression is less than 1, the returned expression will begin at the first character that is specified in value_expression. In this case, the number of characters that are returned is the largest value of either the sum of start_expression and length_expression or 0. If start_expression is greater than the number of characters in the value expression, a zero-length expression is returned.

length_expression

Is a positive integer or bigint expression that specifies how many characters of the value_expression will be returned. If length_expression is negative, an error is generated and the statement is terminated. If the sum of start_expression and length_expression is greater than the number of characters in value_expression, the whole value expression beginning at start_expression is returned.



now the Query should be like this..

SELECT SUBSTRING(@FullName, LASTINDEX(@FullName,'/'1, LEN(@FullName))


Now write a function for finding the lastindex..

CREATE FUNCTION dbo.LASTINDEX(@STRING VARCHAR(8000), @CHAR CHAR)
RETURNS INT
AS
BEGIN
RETURN LEN(@STRING) – (CHARINDEX(@CHAR, REVERSE(@STRING))-1)
END

hope this helps you...
  Vickey F replied to Kishore Rajendran
17-May-11 05:54 AM

try this-

SELECT FieldName ,  IIF(instrrev(FieldName, '\') > 0 ,  mid( FieldName,  instrrev( FieldName, '\')+1) , '') As FileName
FROM TableName
  Vickey F replied to Kishore Rajendran
17-May-11 05:58 AM
try this also-

Select right([FieldName],len([fieldname])-instrrev([fieldname],"\")) as fileName from tablename
Create New Account
help
Transact SQL and selecting SQL Server instances SQL Server Is there anyway to specify what SQL Server instance you want to connect to from inside of a SQL Server Transact-SQL script
Alias for Linked SQL Server? SQL Server Hi, I'm trying to connect to a linked SQL Server 2008 from my local SQL = Server 2008. Everything seems to work fine so far but I'm having the following = problem
Where is my SQL Server 2005 ? SQL Server I installed SQL Server 2005 on my machine, but when I go to the SQL Server Management Studio and connect to the Object Explorer and select my Server (there are 2
Rights for Linked Server SQL Server SQL Server 2005 linked to DB2. . . . . . The queries are successful when procs that access data via the linked server are run by System Administrator. Standard users get the following. . .error code SQL1092N Access Denied. THKS SQL Server Security Discussions SQL Server 2005 (1) Windows Server 2003 (1) X64 (1) €œOpenQuery” (1
Sql Server 2008 RCO]Where is SSMS ? SQL Server Hi there, a very simple question: I cannot find the SSMS component during the Server 2008 RC0 installation process. Is it on a separate download ? Thanks a lot SQL Server Tools Discussions SQL Express 2008 (1) SQL Server 2005 (1) SQL Server 2000 (1) SQL Server 2008 (1