Getting "#ERROR" in certain fields when using Split function in SSRS - sql-server

I am using a split function to separate a column with two street addresses.
The information is separated by ,.
Some of the rows only have one address associated with them.
In those rows for my Street Address 2, I'm getting #ERROR when I want it to be null.
I've tried an IIF() statement for the expression, but I am having trouble with it.
Split(Fields!Street.Value, ",").GetValue(2)

(Use a custom function for each Address.
Adapted from: Split String
Public Function GetAddress1(ByVal a as String)
Dim b() as string
b=Split(a,",")
Dim str_1(b.Length) As String
Dim i As Integer
For i = 0 To b.Length - 1
str_1(i) = b(i).Split(",")(0)
Next
return str_1
End Function
Public Function GetAddress2 (ByVal a as String)
Dim b() as string
b=Split(a,",")
Dim str_1(b.Length) As String
Dim i As Integer
For i = 0 To b.Length - 1
str_1(i) = b(i).Split(",")(1)
Next
return str_1
End Function

Unlike the If statement, IIf statements evaluate all code paths even though only one code path is used. This means that an error in an unused code-path will bubble up to an error in the IIf statement, preventing it from executing correctly.
To fix this, you need to use functions that won't throw an error when there is nothing to split.
Here is an example of code that should do what you want:
=IIf(
InStr(
InStr(
Parameters!Street.Value
, ","
) + 1
,
Parameters!Street.Value
, ","
) = 0
, Nothing
, Right(
Parameters!Street.Value
, Parameters!Street.Value.ToString().Length - (
InStr(
InStr(
Parameters!Street.Value
, ","
) + 1
,
Parameters!Street.Value
, ","
)
)
)
)
Let's break this down.
I've used a combination of InStr(), Right(), Length(), and IIf() functions to split the string without throwing an error.
InStr() is used to find the position of the string "," within the address. This returns 0 rather than an error if it can't find the string.
InStr(Parameters!Street.Value, ",")
Since you appear to be looking for the second comma in your split function you will need to nest the InStr function. Use the location of the first comma as the start location to search for the second comma. Don't forget to +1 or you will find the first comma again.
InStr(InStr(Parameters!Street.Value, ",") + 1, Parameters!Street.Value, ",")
Now you can find the second comma without throwing an error even if no commas exist.
Based on the location of the second comma use the Right() function to grab all characters to the right of the second comma. Since Right() needs to know how many characters from the end rather than from the beginning, you will need to subtract the location of the comma from the Length() of the string. This effectively splits the string at the comma.
Right(
Parameters!Street.Value
, Parameters!Street.Value.ToString().Length - (
InStr(InStr(Parameters!Street.Value, ",") + 1, Parameters!Street.Value, ","))
)
)
If you have more than 2 commas you can grab just the string between the 2nd and 3rd comma by following up with a Left() function that finds the location of the 3rd comma.
Now you can use your IIf() function to return NULL (Nothing) if there is not a 2nd comma. The function at the top shows how this all fits together.
This could be cleaned up by using functions, but the provided code shows you how it can be done.

Related

Underscore in Where clause yields unexpected result, why? [duplicate]

This question already has answers here:
LIKE not working in TSQL
(3 answers)
Closed 3 years ago.
I want to find all tables starting with TB_, hence I've wrote following script:
select *
from INFORMATION_SCHEMA.TABLES
where TABLE_NAME like 'TB_%'
To my surprise I got following result:
TB103_xxx
TB037_bbb
TB104_ccc
I'm curious why?
It means any single character in combination with a like. See
MSDN - LIKE (Transact-SQL)
% - Any string of zero or more characters.
_ - Any single character. _a will match aa, ba etc.
[ ] - Any single character within the specified range ([a-f]) or set ([abcdef]).
[^] - Any single character not within the specified range ([^a-f]) or set ([^abcdef]).
You could use [_] to match a underscore, so like 'TB[_]%'
Or you could use LIKE 'TB\_%' ESCAPE '\'. (thanks to Jeroen Mostert)
This is why because you used the underscore (_) symbol. It means the string Allows you to match on a single character.
Check this SQL LIKE Operator
Better you should use WHERE COLUMN_NAME LIKE 'TB[_]%' or WHERE COLUMN_NAME LIKE 'TB\_%'
% - The percent sign represents zero, one, or multiple characters.
_ - The underscore represents a single character.
[] - Any single character within the specified range ([a-f]) or set ([abcdef]).
[^] - Any single character not within the specified range ([^a-f]) or set ([^abcdef]).
Here is some examples
WHERE CustomerName LIKE 'a%' Finds any values that start with "a"
WHERE CustomerName LIKE '%a' Finds any values that end with "a"
WHERE CustomerName LIKE '%or%' Finds any values that have "or" in any position
WHERE CustomerName LIKE '_r%' Finds any values that have "r" in the second position
WHERE CustomerName LIKE 'a_%' Finds any values that start with "a" and are at least 2 characters in length
WHERE CustomerName LIKE 'a%o' Finds any values that start with "a" and ends with "o"
WHERE CustomerName LIKE '[a-e]arsen' Finds any values that end with "arsen" and starting with any single character between "a" and "e"
WHERE CustomerName LIKE '[^a-e]arsen' Finds any values that end with "arsen" and starting with any single character isn't between "a" and "e".

Multiple line strings in Apache Zeppelin

I have a very long string that must be broken into multiple lines. How can I do that in zeppelin?
The error is error: missing argument list for method + in class String:
Here is the more complete error message:
<console>:14: error: missing argument list for method + in class String
Unapplied methods are only converted to functions when a function type is expected.
You can make this conversion explicit by writing `$plus _` or `$plus(_)` instead of `$plus`.
val q = "select count(distinct productId),count(distinct date),count(distinct instock_inStockPercent), count(distinct instock_totalOnHand)," +
In Scala (using Apache Zeppelin as well as otherwise), you can write expressions covering multiple lines by wrapping them in parentheses:
val text = ("line 1"
+ "line 2")
Using parentheses
As Theus mentioned. One way is parentheses.
val text = ("line 1" +
"line 2")
Actually all multiline statements which break by semantics can be included by parentheses. like.
(object.function1()
.function2())
Using """
For multiline string. We can use """, like this,
val s = """line 1
line2
line3"""
The leading space before line2 and line3 will be included. If we don't want to to have the leading spaces. We can use like this.
val s = """line 1
|line2
|line3""".stripMargin
Or using different strip character
val s = """line 1
$line2
$line3""".stripMargin('$')

SQL Select statement until a character

I'm looking to extract all the text up until a '\' (backslash).
The substring is required to remove all proceeding characters (17 in total) and so I would like to return all after the 17th until it comes across a backslash.
I've tried using charindex but it doesn't seem to stop at the \ it returns characters afterward. My code is as follows
SELECT path, substring(path,17, CHARINDEX('\',Path)+ LEN(Path)) As Data
FROM [Table].[dbo].[Projects]
WHERE Path like '\ENQ%\' AND
Deleted = '0'
Example
The below screen shot shows the basic query and result i.e the whole string
I then use substring to remove the first X characters as there will always be the same amount of proceeding characters
But what Im actually after is (based on the above result) the "Testing 1" "Testing 2" and "Testing ABC" section
The substring is required to remove all proceeding characters (17 in total) and so I would like to return all after the 17th until it comes across a backslash.
select
substring(path,17,CHARINDEX('\',Path)-17)
from
table
To overcome Invalid length parameter passed to the LEFT or SUBSTRING function error, you can use CASE
select
substring(path,17,
CASE when CHARINDEX('\',Path,17)>0
Then CHARINDEX('\',Path)-17)
else VA end
)
from
table

SQL: Fix for CSV import mistake

I have a database that has multiple columns populated with various numeric fields. While trying to populate from a CSV, I must have mucked up assigning delimited fields. The end result is a column containing It's Correct information, but also contains the next column over's data- seperated by a comma.
So instead of Column UPC1 containing "958634", it contains "958634,95877456". The "95877456" is supposed to be in the UPC2 column, instead UPC2 is NULL.
Is there a way for me to split on the comma and send the data to UPC2 while keeping UPC1 data before the comma in tact?
Thanks.
You can do this with string functions. To query the values and verify the logic, try this:
SELECT
LEFT(UPC1, CHARINDEX(',', UPC1) - 1),
SUBSTRING(UPC1, CHARINDEX(',', UPC1) + 1, 1000)
FROM myTable;
If the result is what you want, turn it into an update:
UPDATE myTable SET
UPC1 = LEFT(UPC1, CHARINDEX(',', UPC1) - 1),
UPC2 = SUBSTRING(UPC1, CHARINDEX(',', UPC1) + 1, 1000);
The expression for UPC1 takes the left side of UPC1 up to one character before the comma.
The expression for UPC2 takes the remainder of the UPC1 string starting one character after the comma.
The third argument to SUBSTRING needs some explaining. It's the number of characters you want to include after the starting position of the string (which in this case is one character after the comma's location). If you specify a value that's longer than the string SUBSTRING will just return to the end of the string. Using 1000 here is a lot easier than calculating the exact number of characters you need to get to the end.

Validate the first part of a splitted string

I need to validate in my query if the value of a string (the first part) is equal to a definited value, for instance:
String
----------
F11-EDEDED
F1-SAFSDA
F455-ADADD
F11-ASDA-FAFA
And validate when the string is F11, i was searching something like split on vba, but i can't find it.
Im working with :
Case when ("splitted string") =F11 then X)
Use a Left() and Charindex() to grab the beginning of your strings.
Declare #str varchar(100)='F11-ASDA-FAFA'
Select #str,Case When left(#str,charindex('-',#str)-1)='F11' Then 1 Else 0 End

Resources