开发者

Convert SQL string to list of characters

In a stored procedure I'm writing, I need to convert a string (e.g. 'ABCD') to a list of its component characters (e.g. ('A','B','C','D')). Is there an easy way to go about doing t开发者_JS百科his?

(Using T-SQL in SQL Server 2008.)


DECLARE @Str varchar(100)
DECLARE @StrT varchar(100)

SET @Str = 'ABCDEFG'

WHILE LEN(@Str) > 0
 BEGIN
 SET @StrT = LEFT(@Str, 1)
 RAISERROR (@StrT, 0, 0) WITH NOWAIT
 SELECT @Str = RIGHT(@Str, (LEN(@STR) - 1))
 END

You can modify this as needed. You didn't really specify what you needed to do with the letters so this just prints them out to the message console.


DECLARE @MyString varchar(100)
SET @MyString = 'ABCD'

WHILE LEN(@MyString) > 0 
 BEGIN
 SELECT LEFT(@MyString, 1)
 SET @MyString = RIGHT(@MyString, (LEN(@MyString) - 1))
END

This works in SQL Server 2008.


Building off of JNK's answer:

DECLARE @start nvarchar(MAX);
DECLARE @output nvarchar(MAX);

SELECT @start = 'ABCDEFG', @output = '';

WHILE LEN(@start) > 0
    BEGIN
        SET @output = @output + '''' + LEFT(@start, 1) + ''',';
        SELECT @start = RIGHT(@start, (LEN(@start) - 1))
    END

SELECT CASE WHEN LEN(@output) > 0 THEN LEFT(@output, (LEN(@output) - 1)) ELSE NULL END;

This will get you the formatting you wanted.

Personally I prefer the following since it is easier to work with tabular data:

DECLARE @start nvarchar(MAX);
DECLARE @output TABLE (value nchar(1));

SET @start = 'ABCDEFG'+NCHAR(1121);

WHILE LEN(@start) > 0
    BEGIN
        INSERT INTO @output (value) VALUES (LEFT(@start, 1));
        SELECT @start = RIGHT(@start, (LEN(@start) - 1))
    END

SELECT value, CAST(value AS varbinary(4)) AS hex FROM @output;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜