I have a sql string parameter @branchNumber = '12,23,45'
I am looking for a query that will take my @branchNumber parameter as input and throw back a formatted result that looks as below:
[Branch].[Branch Number].&[12], [Branch].[Branch Number].&[23], [Branch].[Branch Number].&[45]
So basically for each branch add [Branch].[Branch Number].&[<branchNumber>],
I have tried using substring as below:
ALTER FUNCTION AR_BI_SplitBranchesString
(
@Input NVARCHAR(MAX),
@Character CHAR(1)
)
RETURNS NVARCHAR(MAX)
AS
BEGIN
DECLARE @StartIndex INT, @EndIndex INT, @result NVARCHAR(MAX)
SET @StartIndex = 1
--IF SUBSTRING(@Input, LEN(@Input) - 1, LEN(@Input)) <> @Character
--BEGIN
-- SET @Input = @Input + @Character
--END
WHILE CHARINDEX(@Character, @Input) > 0
BEGIN
SET @EndIndex = CHARINDEX(@Character, @Input)
SET @result = '[Branch].[Branch Number].&[' + (SELECT SUBSTRING(@Input, @StartIndex, @EndIndex - 1)) + '],'
SET @Input = SUBSTRING(@Input, @EndIndex + 1, LEN(@Input))
END
RETURN @result
END
GO
But for SELECT dbo.AR_BI_SplitBranchesString('12,54', ',') the result returned is
[Branch].[Branch Number].&[12],
Only returns the first branch. I have it is because SET @Input being modified again. But any assistance would be appreciated. I am using SQL Server 2014.
Thanks
EDIT:
I had a CTE that did something similar, but was getting branch number from another table. I cant find a way to implement it in case of a string.
the cte is as below:
ALTER FUNCTION [dbo].[AR_Fn_BI_GetOperatorBranchList]
(
-- Add the parameters for the function here
@operatorId varchar(20),
@applicationName varchar(100)
)
RETURNS varchar(max)
AS
BEGIN
declare @branchList as varchar(max)
;WITH cte (FId, branchNumbers) AS
(
SELECT 1, CAST('' AS NVARCHAR(MAX))
UNION ALL
SELECT B.FId + 1, B.branchNumbers + '[Branch].[Branch Number].&[' + cast(A.branchNumber as varchar) + '],'
FROM
(
SELECT Row_Number() OVER (ORDER BY Id) AS RN, cast(branchNumber as varchar(8)) as branchNumber
FROM <AnotherTable>
where OperatorId = @operatorId
and [Application] = @applicationName) A
INNER JOIN cte B ON A.RN = B.FId
)
SELECT top 1 @branchList = '{' + subString(branchNumbers, 1, len(branchNumbers) - 1)+ '}'
FROM cte
ORDER BY FId DESC
option (maxrecursion 0)
-- Return the result of the function
RETURN @branchList
END