如何拆分字符串以便访问项目 x? [英] How do I split a string so I can access item x?

查看:20
本文介绍了如何拆分字符串以便访问项目 x?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用 SQL Server,如何拆分字符串以便访问项目 x?

Using SQL Server, how do I split a string so I can access item x?

取一个字符串Hello John Smith".如何按空格拆分字符串并访问应返回John"的索引 1 处的项目?

Take a string "Hello John Smith". How can I split the string by space and access the item at index 1 which should return "John"?

推荐答案

您可以在 用于解析分隔字符串的 SQL 用户定义函数 很有帮助(来自 代码项目).

你可以使用这个简单的逻辑:

You can use this simple logic:

Declare @products varchar(200) = '1|20|3|343|44|6|8765'
Declare @individual varchar(20) = null

WHILE LEN(@products) > 0
BEGIN
    IF PATINDEX('%|%', @products) > 0
    BEGIN
        SET @individual = SUBSTRING(@products,
                                    0,
                                    PATINDEX('%|%', @products))
        SELECT @individual

        SET @products = SUBSTRING(@products,
                                  LEN(@individual + '|') + 1,
                                  LEN(@products))
    END
    ELSE
    BEGIN
        SET @individual = @products
        SET @products = NULL
        SELECT @individual
    END
END

这篇关于如何拆分字符串以便访问项目 x?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆