使用 SQL 服务器从一个字符串中提取一个子字符串,该子字符串位于不同的位置
Extract a substring from a string that the substring is at different position using SQL Server
我在 SQL 服务器上遇到了一个棘手的问题,一直在处理但无法解决。
我想从原始字符串中提取一个数字子字符串(并放入一个新字段),该子字符串位于原始字符串的不同位置。子串以数字开头,子串长度为4。如果子串长度小于4则返回NULL。这背后的原因是人们以不同的方式输入数据,但规范是有一个包含 4 位数字的数字字符串。
这是 table TB_SAMPLE
上的数据
Product Sample
A26 #S #3455 Bag1
A26 Bag 1 #S 3455 Flush 32
MWP1 #T 3457 Bag3
MIP2 Test #S3457 Bag2 342
AMP2 Test#S #3458 Test546
CMP3 Test S 5658 Test
CMP2 Sample2 E 552 Sample2
CMP3 Sample3 E 553 Sample3
想要的结果如下
Product Sample Sample_Extract
A26 #S #3455 Bag1 3455
A26 Bag 1 #S 3455 Flush 32 3455
MWP1 #T 3457 Bag3 3457
MIP2 Test #S3457 Bag2 342 3457
AMP2 Test#S #3458 Test546 3458
CMP3 Test S 5658 Test 5658
CMP2 Sample2 E 552 Sample2 NULL
CMP3 Sample3 E 553 Sample3 NULL
我试过使用内置函数,例如 SUBSTRING、CHARINDEX、LOCATE、LEN... 以及创建的用户函数,但没有帮助
如果你愿意帮助我并想要创建包含上述数据的 table,下面是脚本
CREATE TABLE TB_SAMPLE
(
Product nvarchar(50),
Sample nvarchar(30)
)
INSERT INTO tb_sample VALUES('A26','#S #3455 Bag1')
INSERT INTO tb_sample VALUES('A26','Bag 1 #S 3455 Flush 32')
INSERT INTO tb_sample VALUES('MWP1','#T 3457 Bag3')
INSERT INTO tb_sample VALUES('MIP2','Test #S3457 Bag2 342')
INSERT INTO tb_sample VALUES('AMP2','Test#S #3458 Test546')
INSERT INTO tb_sample VALUES('CMP3','Test S 5658 Test')
INSERT INTO tb_sample VALUES('CMP2','Sample2 E 552 Sample2')
INSERT INTO tb_sample VALUES('CMP3','Sample3 E 553 Sample3')
非常感谢任何帮助!
谢谢
获取模式的位置,然后使用SUBSTRING
:
SUBSTRING(Sample,NULLIF(PATINDEX('%[0-9][0-9][0-9][0-9]%',Sample),0),4)
NULLIF
在没有 4 位数字的情况下 return NULL
。
我在 SQL 服务器上遇到了一个棘手的问题,一直在处理但无法解决。
我想从原始字符串中提取一个数字子字符串(并放入一个新字段),该子字符串位于原始字符串的不同位置。子串以数字开头,子串长度为4。如果子串长度小于4则返回NULL。这背后的原因是人们以不同的方式输入数据,但规范是有一个包含 4 位数字的数字字符串。
这是 table TB_SAMPLE
上的数据Product Sample
A26 #S #3455 Bag1
A26 Bag 1 #S 3455 Flush 32
MWP1 #T 3457 Bag3
MIP2 Test #S3457 Bag2 342
AMP2 Test#S #3458 Test546
CMP3 Test S 5658 Test
CMP2 Sample2 E 552 Sample2
CMP3 Sample3 E 553 Sample3
想要的结果如下
Product Sample Sample_Extract
A26 #S #3455 Bag1 3455
A26 Bag 1 #S 3455 Flush 32 3455
MWP1 #T 3457 Bag3 3457
MIP2 Test #S3457 Bag2 342 3457
AMP2 Test#S #3458 Test546 3458
CMP3 Test S 5658 Test 5658
CMP2 Sample2 E 552 Sample2 NULL
CMP3 Sample3 E 553 Sample3 NULL
我试过使用内置函数,例如 SUBSTRING、CHARINDEX、LOCATE、LEN... 以及创建的用户函数,但没有帮助
如果你愿意帮助我并想要创建包含上述数据的 table,下面是脚本
CREATE TABLE TB_SAMPLE
(
Product nvarchar(50),
Sample nvarchar(30)
)
INSERT INTO tb_sample VALUES('A26','#S #3455 Bag1')
INSERT INTO tb_sample VALUES('A26','Bag 1 #S 3455 Flush 32')
INSERT INTO tb_sample VALUES('MWP1','#T 3457 Bag3')
INSERT INTO tb_sample VALUES('MIP2','Test #S3457 Bag2 342')
INSERT INTO tb_sample VALUES('AMP2','Test#S #3458 Test546')
INSERT INTO tb_sample VALUES('CMP3','Test S 5658 Test')
INSERT INTO tb_sample VALUES('CMP2','Sample2 E 552 Sample2')
INSERT INTO tb_sample VALUES('CMP3','Sample3 E 553 Sample3')
非常感谢任何帮助! 谢谢
获取模式的位置,然后使用SUBSTRING
:
SUBSTRING(Sample,NULLIF(PATINDEX('%[0-9][0-9][0-9][0-9]%',Sample),0),4)
NULLIF
在没有 4 位数字的情况下 return NULL
。