简体   繁体   English

T-SQL PATINDEX -1

[英]T-SQL PATINDEX -1

this is my first post here and i'm also a newby in development. 这是我在这里的第一篇文章,我也是开发中的新人。 In any case.. my problem is: 无论如何..我的问题是:

sql statement: sql语句:

SELECT left(clienti.SedeLegaleIndirizzo, patindex('%[0-9]%',clienti.SedeLegaleIndirizzo))
AS indirizzo from Clienti

clienti.SedeLegaleIndirizzo is clienti table and SedeLegaleIndirizzo is the column with the address including streen and number. clienti.SedeLegaleIndirizzoclienti表,而SedeLegaleIndirizzo是具有地址(包括streen和数字)的列。 I want to separate street from number but with my statement i get the street with the first number. 我想将街道与数字分开,但我的声明中我得到了第一个数字的街道。 As i know from charindex i can add -1 to the last parameter but the problem is that it returns me this error if i put that parameter with patindex: 正如我从charindex知道的,我可以在最后一个参数上加上-1,但问题是,如果我将这个参数与patindex一起使用,它将返回此错误:

Msg 537, Level 16, State 2, Line 1
Invalid length parameter passed to the LEFT or SUBSTRING function.

I'm using patindex and not charindex cause i'm searching a number... 我正在使用patindex而不是charindex,因为我正在搜索一个号码...

What is anybody's suggestion? 有人的建议是什么?

It's not entirely clear to me where you are placing the -1 but it looks you are doing this: 我不清楚您将-1放在哪里,但看起来您正在这样做:

SELECT left(clienti.SedeLegaleIndirizzo,
        patindex('%[0-9]%', clienti.SedeLegaleIndirizzo)-1)

This will give an issue when the number is not found, because then patindex() gives 0 and 0-1=-1 . 当找不到数字时,这将产生问题,因为patindex()给出00-1=-1 You can't have a left() with length -1 . 您不能有长度为-1left() My solution in these cases is this: 在这些情况下,我的解决方案是:

SELECT left(SedeLegaleIndirizzo,
        isnull(nullif(patindex('%[0-9]%', SedeLegaleIndirizzo)-1, -1), 0))

This ensures that if the number is not found, in stead of trying to do left(SedeLegaleIndirizzo, -1) the code will result in left(SedeLegaleIndirizzo, 0) and simply give an empty string. 这样可以确保如果未找到该数字,则代替尝试left(SedeLegaleIndirizzo, -1) ,代码将导致left(SedeLegaleIndirizzo, 0)并仅给出一个空字符串。

The reason you're getting the error is most likely due to rows without numbers which would make the result of patindex(...) -1 negative. 出现错误的原因很可能是由于没有数字的行导致patindex(...) -1的结果为负。

One solution is to exclude those rows: 一种解决方案是排除这些行:

SELECT LEFT(clienti.SedeLegaleIndirizzo, PATINDEX('%[0-9]%',clienti.SedeLegaleIndirizzo) - 1) 
AS indirizzo FROM Clienti
WHERE PATINDEX('%[0-9]%',clienti.SedeLegaleIndirizzo) > 0

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM