我正在尝试在列上找到两个字符之间的子字符串 例如
该列有
Bought ____ by manager
Bought ____ by employee
Bought ____ by other
空白总是在Bought和by之间。 我想把空白中的值分开?任何人都可以帮助我
答案 0 :(得分:0)
您的问题有两个标记MySQL/SQL Server
,如果您有SQL Server
,则可以使用SUBSTRING
和PATINDEX
:
CREATE TABLE #tab(col VARCHAR(100));
INSERT INTO #tab
SELECT 'Bought AAAAAAAAA by manager'
UNION ALL SELECT 'Bought BB by employee'
UNION ALL SELECT 'Bought C by other';
SELECT col,
SUBSTRING(col, 8, PATINDEX('% by%', col)-8)
FROM #tab;
的 LiveDemo
强>
输出:
╔═════════════════════════════╦═══════════╗
║ col ║ result ║
╠═════════════════════════════╬═══════════╣
║ Bought AAAAAAAAA by manager ║ AAAAAAAAA ║
║ Bought BB by employee ║ BB ║
║ Bought C by other ║ C ║
╚═════════════════════════════╩═══════════╝
起点固定为8,长度计算为by
减去固定8之前的空间位置。
MySQL
的 LOCATE
版本:
SELECT col,
SUBSTRING(col, 8, LOCATE(' by', col)-8) AS result
FROM tab;
的 SqlFiddleDemo
强>
答案 1 :(得分:0)
SUBSTRING(表达式,开始,长度)
答案 2 :(得分:0)
使用下面提到的代码: -
select left(col1,charindex(' ',col1)-1) as val1, ltrim(substring(col1,charindex(' ',col1),len(col1))) as val2
from mytable