I want to pass a list of int's (comma separated) which is a field in my table
ie. 1234, 2345, 3456, 4567
to my IN
clause in WHERE
. But the list is a string (VARCHAR
), and I'm comparing to an int field. Is there a way for me to convert the list to list of ints?
Enterprise_ID
is INT
Path is a field in the table which is a comma separated string
ie. 1234, 2345, 3456, 4567
SELECT *
FROM tbl_Enterprise
WHERE Enterprise_ID IN ( Path )
My database is Vertica.
To convert comma-delimited string to a list in Python, split the string with the str. split() method. This results in a list of the parts of the strings that were separated by commas.
PySpark SQL provides split() function to convert delimiter separated String to an Array ( StringType to ArrayType ) column on DataFrame. This can be done by splitting a string column based on a delimiter like space, comma, pipe e.t.c, and converting it into ArrayType.
To convert a delimited string to a sequence of strings in C#, you can use the String. Split() method. Since the Split() method returns a string array, you can convert it into a List using the ToList() method.
You can use SPLIT_PART function in vertica to split the comma separated list into rows and insert them into a temp table. Use a query something like this to achieve your goal:
SELECT * FROM tbl_Enterprice WHERE Enterprice_ID IN ( Select Enterprice_ID from temp_table )
Split part function: https://my.vertica.com/docs/7.1.x/HTML/Content/Authoring/SQLReferenceManual/Functions/String/SPLIT_PART.htm
Here is a example of splitting string into rows using split_part:
dbadmin=> SELECT SPLIT_PART('JIM|TOM|PATRICK|PENG|MARK|BRIAN', '|', row_num) "User Names"
dbadmin-> FROM (SELECT ROW_NUMBER() OVER () AS row_num
dbadmin(> FROM tables) row_nums
dbadmin-> WHERE SPLIT_PART('JIM|TOM|PATRICK|PENG|MARK|BRIAN', '|', row_num) <> '';
User Names
------------
JIM
TOM
PATRICK
PENG
MARK
BRIAN
(6 rows)
I would consider these two solutions to be anti-patterns and would recommend testing them for performance.
The first method uses functions that come in the flex table package.
SELECT values::INT as var1
FROM (
SELECT MapItems(v1) OVER () AS (keys, values)
FROM (
SELECT MapDelimitedExtractor( '1234, 2345, 3456, 4567'
USING PARAMETERS DELIMITER=',') AS v1
) AS T
) AS T2
WHERE REGEXP_SUBSTR(values,'\d+',1) IS NOT NULL;
var1
------
1234
2345
3456
4567
(4 rows)
The second method uses functions that comes in the text index package.
SELECT words::INT AS var1
FROM (
SELECT TxtIndex.StringTokenizerDelim('1234, 2345, 3456, 4567',',')
OVER() AS (words, input_string)
) AS T
WHERE REGEXP_SUBSTR(words, '\d+',1) IS NOT NULL;
var1
------
1234
2345
3456
4567
(4 rows)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With