[英]Get a particular string from an expression in a column in T-SQL
我的SQL Server數據庫表中有一列,其中包含“ |” (管道)分隔的值。
例:
'FirstName |testname| lastName | lastname | roll |ee097765 | 100 | end'
'FirstName |testname1| lastName | lastname1 | roll2 |ee0977652 | 1100 | end'.
我只想使用T-SQL提取標記,其中我的輸出列將只有標記,即僅100或隨后的1100。 在Oracle中,我們可以使用
SUBSTRING_INDEX
函數,但在T-SQL中不可用。
誰能指出我該怎么做?
SUBSTRING_INDEX(SUBSTRING_INDEX(field, '|', 3), '|', -1)
declare @TEST table(val nvarchar(1000))
insert into @TEST
values ('FirstName |testname| lastName | lastname | roll |ee097765 | 100 | end'),
('FirstName |testname1| lastName | lastname1 | roll2 |ee0977652 | 1100 | end')
SELECT Value
FROM @TEST CROSS APPLY
Split(val,'|')
WHERE ISNUMERIC(Value) = 1
您只需要使用將找到的通用拆分功能: https : //codereview.stackexchange.com/questions/15125/sql-server-split-function
您可以使用SQLCLR函數。 將其應用於SQL Server有一些注意事項。 無論如何,這是查找所需值的變體之一:
public partial class UserDefinedFunctions
{
[SqlFunction]
public static SqlString GetMarkPosition(SqlString sqlString)
{
// Assume there will be no result,
// so initialize return value to null string.
SqlString retVal = SqlString.Null;
// Extract C# string
string input = sqlString.Value;
// I use Regex Split method rather array Split method,
// since Regexe method handles spaces in elegant way.
string pattern = @"\s*\|\s*";
// Get array of values
string[] split = Regex.Split(input, pattern);
// The logic is the following:
// First, we find the marker's position in list.
// The sought value is one index less.
// This process is repeated for each marker.
// If no match is found for any marker,
// the function will just return empty string,
// as we initialized retVal variable.
foreach (string marker in new[] { "100", "1100" })
{
var list = new List<string>(split);
int index = list.IndexOf(marker);
if (index > 0)
{
retVal = new SqlString(list[index - 1]);
break;
}
}
return retVal;
}
}
為了創建此功能,您需要執行幾個步驟。 如果您使用的是SQL Server 2017,則安全模型已更改(例如,請在此處和此處閱讀 ),因此Visual Studio將無法幫助您在SQL Server方面創建程序集-您必須手動進行操作。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.