Sql-Server

從字元串中提取數據庫名稱

  • November 1, 2016

在數據庫中,我們有數據庫欄位類型的完整文件路徑nvarchar(255),結構/數據如下所示:

M:\Blue\Red\Green\Folder\Pink\Purple\Database1.accdb
M:\Blue\Red\Orange\Folder1\Folder2\Folder3\Size\Small\Large\DbTest1232323Test.accdb

我的問題是,我怎樣才能只提取數據庫名稱——只提取這個:

  • 數據庫1.accdb
  • DbTest1232323Test.accdb

由於數據庫的名稱可能不同,我不能只使用一個RIGHT()函式。

有沒有辦法我可以以某種方式使用萬用字元RIGHT()來表示“將所有內容拉到最後一個\”?

這個應該可以的。您需要最後一列 (FileName_Only)。

SELECT f.physical_name,
   REVERSE(f.physical_name) AS physical_name_Reversed,
   CHARINDEX('\', REVERSE(f.physical_name)) AS First_Backslash_When_Reversed,
   LEFT(REVERSE(f.physical_name), CHARINDEX('\', REVERSE(f.physical_name)) - 1) AS FileName_Only_Reversed,
   REVERSE(LEFT(REVERSE(f.physical_name), CHARINDEX('\', REVERSE(f.physical_name)) - 1)) AS FileName_Only
FROM sys.database_files f

這是另一種選擇。程式碼有點精簡:

SELECT 
   f.physical_name,
   REVERSE(f.physical_name) AS physical_name_Reversed,
   CHARINDEX('\', REVERSE(f.physical_name)) AS First_Backslash_When_Reversed,
   RIGHT(f.physical_name, CHARINDEX('\', REVERSE(f.physical_name)) - 1) AS FileName_Only
FROM sys.database_files f

引用自:https://dba.stackexchange.com/questions/153775