i'm trying to split this string "1,1_5,2_3,4" first on '_' and then split the sub string on ',' so it will be like "1,1_5,2_3,4" split-ed on '_' first so it will give this sub string "1,1" then this sub string split-ed on ',' and then insert the split-ed sub string "1 1" into temp table like this
INSERT INTO [dbo].[TEST] ([X],[Y])
VALUES (@X,@Y)
i did this with only split on one delimiter ',' like this first i create a table Split function
ALTER FUNCTION [dbo].[Split]
(
-- Add the parameters for the function here
@RowData nvarchar(2000),
@SplitOn nvarchar(5)
)
RETURNS @RtnValue table
(
Id int identity(1,1),
Data nvarchar(100)
)
AS
BEGIN
-- Declare the return variable here
Declare @Cnt int
Set @cnt = 1
While(charindex(@SplitOn,@RowData) > 0)
Begin
Insert Into @RtnValue (data)
Select
Data = ltrim(RTRIM(SUBSTRING(@RowData,1,CHARINDEX(@SplitOn,@RowData)-1)))
set @RowData = SUBSTRING(@RowData,CHARINDEX(@SplitOn,@RowData)+1,len(@RowData))
set @Cnt = @Cnt + 1
End
insert into @RtnValue(data)
select Data = ltrim(RTRIM(@RowData))
RETURN
END
then i create this stored procedure
ALTER PROCEDURE [dbo].[uspTest]
-- Add the parameters for the stored procedure here
@StringOFXIDs nvarchar(2000)
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
DECLARE @SOMETABLE TABLE(ID INT IDENTITY(1,1) UNIQUE, XID INT);
DECLARE @XCOUNT INT;
DECLARE @XCURRENT INT;
DECLARE @XCOUNTER INT = 1;
-- Insert statements for procedure here
INSERT INTO @SOMETABLE([XID])
SELECT [Data] FROM [dbo].[Split](@StringOFXIDs,',');
SELECT @XCOUNT = COUNT(1) FROM @SOMETABLE;
WHILE (@XCOUNTER <= @XCOUNT)
BEGIN
SELECT @XCOUNTER = [XID]
FROM @SOMETABLE
WHERE [ID] = @XCOUNTER
INSERT INTO [dbo].[TEST] ([X])
VALUES (@XCOUNTER)
SELECT @XCOUNTER +=1;
END
END
--EXEC [dbo].[uspTest] '1,2,3,4'
and then execute this stored procedure and every thing work but i can't figure out how to split the string on two characters or delimiters and then inserted to temp table thanks for any help in advance.