SQL Server:根据空间将字符串拆分为 1 列

问题描述 投票:0回答:1

我正在寻找一种好方法来将基于空格\下划线的字符串拆分为一列。

例如:

string name = 'tom arnold lee ford'
into named_columns

然后进行查询:

select name from named_columns

输出:

tom
arnold
lee
ford

谢谢你...

split sql-server-2014
1个回答
0
投票
-- Declare the variable
DECLARE @name VARCHAR(MAX) = 'tom arnold lee ford';

-- Create a temporary table to store the split names
CREATE TABLE #named_columns (name VARCHAR(MAX));

-- Split the string and insert into the table
INSERT INTO #named_columns (name)
SELECT value FROM STRING_SPLIT(@name, ' ') WHERE RTRIM(value) <> '';

-- Retrieve the split names
SELECT name FROM #named_columns;

-- Clean up
DROP TABLE #named_columns;
© www.soinside.com 2019 - 2024. All rights reserved.