如何查找整列的子字符串

时间:2015-12-15 18:53:28

标签: mysql sql sql-server

我正在尝试在列上找到两个字符之间的子字符串 例如

该列有

Bought ____ by manager
Bought ____ by employee
Bought ____ by other

空白总是在Bought和by之间。 我想把空白中的值分开?任何人都可以帮助我

3 个答案:

答案 0 :(得分:0)

您的问题有两个标记MySQL/SQL Server,如果您有SQL Server,则可以使用SUBSTRINGPATINDEX

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(表达式,开始,长度)

来源:https://msdn.microsoft.com/en-us/library/ms187748.aspx

答案 2 :(得分:0)

使用下面提到的代码: -

select left(col1,charindex(' ',col1)-1) as val1, ltrim(substring(col1,charindex(' ',col1),len(col1))) as val2
from mytable