[英]Substring with patindex for substrings' length not working to extract part of a string
I have a table with strings (ItemCode) like:我有一个包含字符串 (ItemCode) 的表,例如:
99XXX123456-789 99XXX123456-789
12ABC221122-987BA1 12ABC221122-987BA1
They are always of a length of 11 characters (upto the - of which they always contain only one), after the - length is variable.它们的长度始终为 11 个字符(直到 - 它们始终只包含一个字符),在 - 之后长度是可变的。 I would like to get the part after the first 5 characters upto the -, like this.
我想得到前 5 个字符之后到 - 的部分,就像这样。
123456 123456
221122 221122
I tried with substring and patindex:我尝试使用 substring 和 patindex:
SELECT SUBSTRING( ItemCode, 6, PATINDEX('%[-]%', ItemCode) - 6 ),
PATINDEX('%[-]%', ItemCode),
ItemCode
FROM TableName
WHERE LEFT(ItemCode, 5) = '99XXX'
Patindex itself returns the correct value (12) but with PATINDEX('%[-]%', ItemCode) - 6 /sql should understand this as 12 - 6 = 6 / SQL Server 2012 gives an error. Patindex 本身返回正确的值 (12),但使用 PATINDEX('%[-]%', ItemCode) - 6 /sql 应该将此理解为 12 - 6 = 6 / SQL Server 2012 给出错误。 I could use 6 as a fix value in the patindex for the length, of course but I want to understand the reason for the error.
当然,我可以在 patindex 中使用 6 作为长度的固定值,但我想了解错误的原因。
But when I am using the same query I am not getting the error:但是当我使用相同的查询时,我没有收到错误:
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'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.