Scenario
According to my existing scenario as shown in the above table STProcedure there could exists combination groups with respect to individual STProcedure. In the above picture it can be seen that the following relationships are true with STProcedureID and GroupID
- A => A_B_C
- B => B_A_E
- C =>
- D => D_B_C_E
- E => D_E_A
Requirement + Initial Solution
It is required that the GroupIDs should be split with the delimiter '_' in a single line query.
I was able to find a solution by using a user defined function as follows
- User defined function - fnSplit
ALTER FUNCTION E1.fnSplit (@sInputList udtStringMax, @sDelimiter udtStringMax = '_')
RETURNS @List TABLE (item udtStringMax,CNT INT IDENTITY(1,1))
BEGIN
DECLARE @sItem udtStringMax
WHILE CHARINDEX(@sDelimiter,@sInputList,0) <> 0
BEGIN
SELECT
@sItem=SUBSTRING(@sInputList,1,CHARINDEX(@sDelimiter,@sInputList,0)-1),
@sInputList=SUBSTRING(@sInputList,CHARINDEX(@sDelimiter,@sInputList,0)+LEN(@sDelimiter),LEN(@sInputList))
IF LEN(@sItem) > 0
INSERT INTO @List SELECT @sItem
END
IF LEN(@sInputList) > 0
INSERT INTO @List SELECT @sInputList -- Put the last item in
RETURN
END
- Single line query was as follows which used fnSplit
SELECT * FROM E1.E_STProcedure WHERE STProcedureID IN
(SELECT item FROM E1.fnSplit((SELECT GroupID FROM E1.E_STProcedure WHERE STProcedureID='||OWNER||'),'_'))
where ||OWNER||
is the individual STProcedureID and E1 is the schema of the DB that I had
Limitations
Since the system was implemented in an MTMS (Multi-Tenant Multi-Schema) environment each query was schema dependant and had more than 100 schemas, the above code would only work for E1 schema.
I came to a conclusion that maybe there exists a workaround to split a string (with delimiter) using a single line query in SQL without the usage of user defined function, because the only other option is to replace and execute the query for each schema with its token.