我有一个包含字符串(ItemCode)的表,如下所示:
99XXX123456-789
12ABC221122-987BA1
它们总是长度为11个字符(直到它们总是只包含一个字符),在-长度是可变的之后。我想得到的部分后,前5个字符到-,像这样。
123456
221122
我尝试使用子字符串和patindex:
SELECT SUBSTRING( ItemCode, 6, PATINDEX('%[-]%', ItemCode) - 6 ),
PATINDEX('%[-]%', ItemCode),
ItemCode
FROM TableName
WHERE LEFT(ItemCode, 5) = '99XXX'Patindex本身返回正确的值( 12 ),但是对于PATINDEX('%-%',ItemCode) -6,/sql应该理解这一点,因为12-6=6/ Server 2012给出了一个错误。当然,我可以在patindex中使用6作为长度的固定值,但我想了解错误的原因。
发布于 2022-12-03 14:41:05
但是,当我使用相同的查询时,我不会得到错误:
create table #temp
(
num varchar(50)
)
--insert into #temp values ('99XXX123456-789')
--insert into #temp values ('12ABC221122-987BA1')
SELECT SUBSTRING( num, 6, PATINDEX('%[-]%', num) - 6 ),
PATINDEX('%[-]%', num),
num
FROM #temp WHERE LEFT(num, 5) = '99XXX'https://stackoverflow.com/questions/74667201
复制相似问题