I have some data as below
ID Data
1 a
1 2
1 b
1 1
2 d
2 3
2 r
Desired Output
ID Data
1 a
1 NULL
1 NULL
1 b
1 NULL
2 d
2 NULL
2 NULL
2 NULL
2 r
What the output is , for the numerics it is replaced with those many null values. E.g. for a numeric value of 2 , it will be 2 null values.
The ddl is as under
Declare @t table(ID int, data varchar(10))
Insert into @t
Select 1, 'a' union all select 1, '2' union all select 1, 'b' union all select 1, '1' union all select 2,'d' union all
select 2,'3' union all select 2, 'r'
select * from @t
Please give a CTE based solution. I already have the procedural approach but I need to have a feel of CTE based solution.
Solution I am using at present
CREATE FUNCTION [dbo].[SPLIT] (
@str_in VARCHAR(8000)
)
RETURNS @strtable TABLE (id int identity(1,1), strval VARCHAR(8000))
AS
BEGIN
DECLARE @tmpStr VARCHAR(8000), @tmpChr VARCHAR(5), @ind INT = 1, @nullcnt INT = 0
SELECT @tmpStr = @str_in
WHILE LEN(@tmpStr) >= @ind
BEGIN
SET @tmpChr = SUBSTRING(@tmpStr,@ind,1)
IF ISNUMERIC(@tmpChr) = 0
INSERT INTO @strtable SELECT @tmpChr
ELSE
WHILE @nullcnt < @tmpChr
BEGIN
INSERT INTO @strtable SELECT NULL
SET @nullcnt = @nullcnt + 1
END
SELECT @ind = @ind + 1, @nullcnt = 0
END
RETURN
END
GO
Invocation
SELECT * from dbo.SPLIT('abc2e3g')
I donot want to do it using function but a CTE solution.
Reason: I am learning CTE and trying to solve problems using it. Trying to come out of procedural/rBar approach.
Thanks
Setup:
Query:
Output:
I added UniqueId as there should be some kind of field that specifies order in the original table.