I'm trying to use LEFT combined with CHARINDEX to extract a substring from a column in a table but its giving the following error
Msg 537, Level 16, State 2, Line 1 Invalid length parameter passed to the LEFT or SUBSTRING function.
select name, left(name, charindex('\',name) - 1) as sub
from sys.servers
However, if i apply same on a single string using a variable it works..
declare @mytext varchar(max)
set @mytext = 'hello\world'
SET @MyText = LEFT(@MyText, CHARINDEX('\', @MyText) - 1)
print @mytext
O/P:
----
hello
Please let me know What i am doing wrong ?
The problem is that name
may not have a backslash. This is easily fixed, but it depends on what you want as a result. This gives the full name when there is no backslash:
select name,
left(name, charindex('\', name + '\') - 1) as sub
from sys.servers;
The problem is that charindex()
returns 0
when the value is not present -- and that is an error as the length for left()
.
what you can do is use IIF for SQL 2012 + or Case to avoid the error when no '\\' inside the text
declare @mytext varchar(max)
set @mytext = 'hello world'
SET @MyText = LEFT(@MyText, iif(CHARINDEX('\', @MyText)>0,CHARINDEX('\', @MyText) - 1,len(@mytext)))
print @mytext
CASE
SET @MyText = LEFT(@MyText,
CASE
WHEN CHARINDEX('\', @MyText) > 0 THEN CHARINDEX('\', @MyText) - 1
ELSE LEN(@mytext)
END)
PRINT @mytext
When it can't find '\\' in name it will give 0 so final result will be left(name,-1) which is invalid. So you need to write code in such a way that if there is -1 you need to treat that as 0. Below code fix that issue.
select name, left(name, ISNULL(NULLIF(charindex('\',name) - 1,-1),0)) as sub from sys.servers
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.