如何在T-SQL中分割字符串并保存到数组中

发布于 2024-10-04 08:27:59 字数 585 浏览 10 评论 0 原文

我正在编写一个游标来从主表填充新表中的数据,该主表包含以下方式的数据

项目 颜色
衬衫 红色、蓝色、绿色、黄色

我想通过获取项目然后将其添加到行中来填充新表数据,根据它包含的每种颜色

项目 颜色
衬衫 红色
衬衫 蓝色
衬衫 绿色
衬衫 黄色

我陷入了如何

  1. 定界/分割“颜色”字符串
  2. 将其保存在数组中
  3. 要在光标中使用它,

因为我将使用嵌套光标来实现此目的。

I am writing a cursor to populate data in new table from main table which contains data in below manner

Item Colors
Shirt Red,Blue,Green,Yellow

I want to populate new Table data by fetching the Item and then adding it in row, according to each color it contains

Item Color
Shirt Red
Shirt Blue
Shirt Green
Shirt Yellow

I am stuck in how to

  1. Delimit/Split "Colors" string
  2. To save it in an array
  3. To use it in cursor

as I am going to use Nested cursor for this purpose.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

萌无敌 2024-10-11 08:28:00

文章 在 Transact SQL 中伪造数组< /a> 详细介绍了解决此问题的几种技术,从使用 PARSENAME() 函数(限制为 5 项)到编写 CLR 函数。

XML 答案是可以针对特定场景选择的详细技术之一。

结合一些技巧,我解决了我的字符串拆分问题,如下所示:

SET NOCOUNT ON;

DECLARE @p NVARCHAR(1000), @len INT;
SET @p = N'value 1,value 2,value 3,value 4,etc';
SET @p = ',' + @p + ',';
SET @len = LEN(@p);

-- Remove this table variable creation if you have a permanent enumeration table
DECLARE @nums TABLE (n int);
INSERT INTO @nums (n)
    SELECT A.n FROM 
    (SELECT TOP 1000 ROW_NUMBER() OVER (ORDER BY TableKey) as n FROM dbo.Table) A
    WHERE A.n BETWEEN 1 AND @len;

SELECT SUBSTRING(@p , n + 1, CHARINDEX( ',', @p, n + 1 ) - n - 1 ) AS "value"
    FROM @nums
    WHERE SUBSTRING( @p, n, 1 ) = ',' AND n < @len;

请注意,考虑到字符串长度限制为 1000,您必须有一个包含 1000 行或更多行的表(示例 tsql 上的 dbo.Table)才能创建表变量 @该样本的编号。在文章中,他们有一个永久的枚举表。

The article Faking Arrays in Transact SQL details SEVERAL techniques to solve this problem, ranging from using the PARSENAME() function (limit to 5 items) to writing CLR functions.

The XML answer is one of the detailed techniques that can be chosen to a specific scenario.

Combining some of the tips, I solved my string split problem like this:

SET NOCOUNT ON;

DECLARE @p NVARCHAR(1000), @len INT;
SET @p = N'value 1,value 2,value 3,value 4,etc';
SET @p = ',' + @p + ',';
SET @len = LEN(@p);

-- Remove this table variable creation if you have a permanent enumeration table
DECLARE @nums TABLE (n int);
INSERT INTO @nums (n)
    SELECT A.n FROM 
    (SELECT TOP 1000 ROW_NUMBER() OVER (ORDER BY TableKey) as n FROM dbo.Table) A
    WHERE A.n BETWEEN 1 AND @len;

SELECT SUBSTRING(@p , n + 1, CHARINDEX( ',', @p, n + 1 ) - n - 1 ) AS "value"
    FROM @nums
    WHERE SUBSTRING( @p, n, 1 ) = ',' AND n < @len;

Note that, considering 1000 your string length limit, you must have a table with 1000 or more rows (dbo.Table on the sample tsql) to create the table variable @nums of this sample. On the article, they have a permanent enumeration table.

指尖上得阳光 2024-10-11 08:28:00

对于那些喜欢保持简单的人:

    -- Here is the String Array you want to convert to a Table
declare @StringArray varchar(max)
set @StringArray = 'First item,Second item,Third item';

-- Here is the table which is going to contain the rows of each item in the String array
declare @@mytable table (EachItem varchar(50))

-- Just create a select statement appending UNION ALL to each one of the item in the array
set @StringArray = 'select ''' + replace(@StringArray, ',', ''' union all select ''') + ''''
-- Push the data into your table
insert into @@mytable exec (@StringArray)

-- You now have the data in an an array inside a table that you can join to other objects
select * from @@mytable

For those who like to keep it simple:

    -- Here is the String Array you want to convert to a Table
declare @StringArray varchar(max)
set @StringArray = 'First item,Second item,Third item';

-- Here is the table which is going to contain the rows of each item in the String array
declare @@mytable table (EachItem varchar(50))

-- Just create a select statement appending UNION ALL to each one of the item in the array
set @StringArray = 'select ''' + replace(@StringArray, ',', ''' union all select ''') + ''''
-- Push the data into your table
insert into @@mytable exec (@StringArray)

-- You now have the data in an an array inside a table that you can join to other objects
select * from @@mytable
極樂鬼 2024-10-11 08:28:00

我刚刚完成了类似的事情,创建临时表以使用链接服务器上的 INFORMATION_SCHEMA 视图复制源表。但这是一个修改版本,用于创建您正在寻找的结果。只需记住在显示“颜色”列时删除最后两个字符即可。

SELECT
    t.Item
    , (
        SELECT 
            x.Color + ', ' AS [data()]
        FROM 
            Items x
        WHERE 
            x.Item = t.Item
        FOR XML PATH(''), TYPE
    ).value('.', 'varchar(max)') AS Colors
FROM 
    Items t
GROUP BY 
    t.Item

I just accomplished something like this to create staging tables to replicate the source tables using the INFORMATION_SCHEMA views on a linked server. But this is a modified version to create the results you are look for. Just remember to remove the last two characters from the Colors column when displaying it.

SELECT
    t.Item
    , (
        SELECT 
            x.Color + ', ' AS [data()]
        FROM 
            Items x
        WHERE 
            x.Item = t.Item
        FOR XML PATH(''), TYPE
    ).value('.', 'varchar(max)') AS Colors
FROM 
    Items t
GROUP BY 
    t.Item
§对你不离不弃 2024-10-11 08:28:00

在 SQL Server 2016+ 中,可以使用 STRING_SPLIT 函数

现在这很容易:

SELECT value 
FROM STRING_SPLIT('Red,Blue,Green,Yellow', ',');

In SQL Server 2016+ one can use STRING_SPLIT function

Now this will be easy:

SELECT value 
FROM STRING_SPLIT('Red,Blue,Green,Yellow', ',');
べ繥欢鉨o。 2024-10-11 08:27:59

使用 Sql Server 2005+ 和 XML 数据类型,您可以查看以下内容

DECLARE @Table TABLE(
        Item VARCHAR(250),
        Colors VARCHAR(250)
)

INSERT INTO @Table SELECT 'Shirt','Red,Blue,Green,Yellow'
INSERT INTO @Table SELECT 'Pants','Black,White'


;WITH Vals AS (
        SELECT  Item,
                CAST('<d>' + REPLACE(Colors, ',', '</d><d>') + '</d>' AS XML) XmlColumn
        FROM    @Table
)
SELECT  Vals.Item,
        C.value('.','varchar(max)') ColumnValue
FROM    Vals
CROSS APPLY Vals.XmlColumn.nodes('/d') AS T(C)

Using Sql Server 2005+ and the XML datatype, you can have a look at the following

DECLARE @Table TABLE(
        Item VARCHAR(250),
        Colors VARCHAR(250)
)

INSERT INTO @Table SELECT 'Shirt','Red,Blue,Green,Yellow'
INSERT INTO @Table SELECT 'Pants','Black,White'


;WITH Vals AS (
        SELECT  Item,
                CAST('<d>' + REPLACE(Colors, ',', '</d><d>') + '</d>' AS XML) XmlColumn
        FROM    @Table
)
SELECT  Vals.Item,
        C.value('.','varchar(max)') ColumnValue
FROM    Vals
CROSS APPLY Vals.XmlColumn.nodes('/d') AS T(C)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文