SQL Server:在关键字之后找到一个子字符串

时间:2018-08-07 14:09:47

标签: sql sql-server sql-server-2008 tsql

我正在尝试在该行上找到密码,我需要在关键字“ password”之后找到一个子字符串。

SQL Server数据库表包含以下示例行:

hello do you have any problems? Password: Qq111222 good luck  tel: 9-189309, email: sso@gmail.com
hello do you have any problems? Password: Aw654371 good luck  tel: 9-189309, email: sso@gmail.com
hello do you have any problems? Password: Zd354321 good luck  tel: 9-189309, email: sso@gmail.com
hello do you have any problems? Password: temporary password good luck  tel: 9-189309, email: sso@gmail.com
hello do you have any problems? Password: temporary password good luck  tel: 9-189309, email: sso@gmail.com

我正在寻找一种方法来找到密码一词之后的10个字符,substring包含数字和字母,是否可以在SQL Server中编写此字符?

我使用以下内容,但有很多不合适的行:

select fields
from table
where fields like '%Password%[a-z,A-Z]%[0-9]%'

2 个答案:

答案 0 :(得分:3)

使用charindex()

select *, substring(fields, charindex('password', fields)+9, 10)
from table t

但是,如果您的字符串中没有password字,这可能会失败,因此,您可以使用charindex()添加预防措施或包含where子句:

select *, substring(fields, charindex('password', fields + 'password')+9, 10)
from table t;

答案 1 :(得分:0)

假设您要在两侧留出空间:

DECLARE @S varchar(8000);
SET @S = 'hello do you have any problems? Password: Qq111222 good luck  tel: 9-189309, email: sso@gmail.com';
SELECT SUBSTRING(@S,PATINDEX('%Password:%',@S) + LEN('Password:'),10);