I have searched everywhere and I cannot find this implementation anywhere.
Let\'s say I have the word: QWERTY
I want to obtain this table:
Please, PLEASE avoid referencing systems tables, specifically system tables in system databases. In fact, the selected answer above probably won't compile in a Visual Studio 2013 Database Project
Table variables are fine, but recursion with a CTE is the answer:
DECLARE @str VARCHAR(max)
SET @str = 'QWERTY AnotherWord'
WITH Split(stpos,endpos)
AS(
SELECT 1 AS stpos, 2 AS endpos
UNION ALL
SELECT endpos, endpos+1
FROM Split
WHERE endpos <= LEN(@str)
)
SELECT
'character' = SUBSTRING(@str,stpos,COALESCE(NULLIF(endpos,0),LEN(@str)+1)-stpos)
,'charindex' = stpos
FROM Split
That said, the use for the code above is to get a table full of letters representing different permissions for a user. That is not the way to do this. Make a table with an ID, a permission code and a description then make a linking table between the users table and the new permissions table. this gives you the same abilities and doesn't make you solve dumb problems like this.
Here is a table-valued function (derived from aF's temp table implementation). It differs slightly from aF's implementation in that it starts with @count=1
; this excludes an extraneous leading space.
CREATE FUNCTION [dbo].[Chars] (@string VARCHAR(max))
RETURNS @chars TABLE (character CHAR)
AS
BEGIN
DECLARE @count INT,
@total INT
SELECT @total = Len(@string),
@count = 1
WHILE @count <= @total
BEGIN
INSERT INTO @chars
SELECT Substring(@string, @count, 1)
SELECT @count = @count + 1
END
RETURN
END
Usage:
SELECT * FROM dbo.chars('QWERTY AnotherWord')
Declare @word nvarchar(max)
Select @word = 'Hello This is the test';
with cte (Number)as
(Select 1
union all
select Number +1 From cte where number <len(@word)
)
select * from Cte Cross apply (Select SUBSTRING(@word,number,1 ) ) as J(Letter)
Do it like this:
select substring(a.b, v.number+1, 1)
from (select 'QWERTY AnotherWord' b) a
join master..spt_values v on v.number < len(a.b)
where v.type = 'P'
Here you have it:
create table #words (
character varchar(1)
)
declare @test varchar(10)
select @test = 'QWERTY'
declare @count int, @total int
select @total = len(@test), @count = 0
while @count <= @total
begin
insert into #words select substring(@test, @count, 1)
select @count = @count + 1
end
select * from #words
drop table #words