This Question is pretty much answered in this forum but for my situation which is exactly the same the answers I find here are not working.
I'm trying to remove all the characters after the pipe " | " in sql server. Any suggestions why it's not working?
query that i'm using:
SELECT left(name, charindex('|',name) -1) from table1
Error:
Invalid length parameter passed to the LEFT or SUBSTRING function.
table1:
name
----
jack| rose|
wil |jo|rdy
karl||jay
jo smith
jjill
raj |kumar
Desired output:
name
----
jack
wil
karl
jo smith
jjill
raj
6条答案
按热度按时间wz8daaqr1#
try:
kq4fsx7k2#
Think you're almost there - you just need to filter to ensure you aren't passing a negative number to the LEFT e.g.,
Remember charindex is 0 if it doesn't exist in string, then you subtract 1. This means you're trying to do a LEFT(name, -1) which is invalid.
To get your full output (with all rows, regardless of the | symbol) you can use it in a CASE instead.
Edit: Here's a db<>fiddle with results.
zf2sa74q3#
You can try the below -
55ooxyrt4#
based on your query, its expecting values to have
|
always. So this will error onname = jo smith'. Use
select caseto solve this.
kyks70gy5#
Instead of using
LEFT
, use a combination ofSTUFF
andISNULL
.While
LEFT
will raise the "Invalid length parameter passed to the left function." error if it gets a negative length parameter,STUFF
will simply return null if it's starting position argument is less than less than 1.This means that if the original value doesn't contain
|
andcharindex
return0
,stuff
will simply returnnull
, and you can useISNULL
to return the original value in this case.First, create and populate sample table (Please save us this step in your future questions):
The query:
Results:
flseospp6#
You can use this in a calculated field as:
Or as a SQL statement: