STRING_SPLIT() is one of the most used string functions, which splits the string based on one character separator. Earlier I have written an article about it in detail.
Recently, I was using STRING_SPLIT() function and I came across given below error and the reason is I used two characters separator which is NOT valid for STRING_SPLIT() function:
Error :
Procedure expects parameter ‘separator’ of type ‘nchar(1)/nvarchar(1)’.
DECLARE @String AS VARCHAR(50); SET @String = '1:30PM2:30PM3:30PM4:30PM5:30PM6:30PM7:30PM'; SELECT * FROM STRING_SPLIT(@String, 'PM'); GO --OUTPUT

Solution:
As per SQL documentation, STRING_SPLIT() function can take only one character in the separator argument.
Now, in order to solve this issue, we are going to use REPLACE() function to replace the two characters separator “PM” to one character separator “|“. Also, make sure that you MUST replace with a separator which is NOT available in your data, I used “|” which is not available in my entire data. After that, we can simply split the string using STRING_SPLIT() function as shown in the below example.
--Declare a variable DECLARE @String AS VARCHAR(50); --Set variable value SET @String = '1:30PM2:30PM3:30PM4:30PM5:30PM6:30PM7:30PM'; --Replace PM with another single character separator '|' SET @String = LEFT(REPLACE(@String,'PM','|'),LEN(REPLACE(@String,'PM','|'))-1); --Apply String_Split function SELECT * FROM STRING_SPLIT(@String, '|'); GO --OUTPUT

Conclusion:
Try to use one character separator in STRING_SPLIT() function, then you will not get above error.
Leave a Reply