T-SQL Split Word into characters

前端 未结 5 1226
太阳男子
太阳男子 2020-11-28 12:19

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:

5条回答
  •  余生分开走
    2020-11-28 12:31

    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.

提交回复
热议问题