SQL Server 中的字符串分割
我有一个关于 SQL Server 的问题:如何使用 _
分割字符串并获取所需的格式。
如果我们没有 - 符号,则保留空值。
表:
CREATE TABLE [dbo].[student]
(
[sid] [int] NULL,
[course] [varchar](500) NULL,
[name] [varchar](50) NULL
)
INSERT INTO [dbo].[student] ([sid], [course], [name])
VALUES (1, N'database-sql;FE-Java', N'abc')
INSERT INTO [dbo].[student] ([sid], [course], [name])
VALUES (2, N'FE-net;database-oracle;FE-python', N'xyz')
INSERT INTO [dbo].[student] ([sid], [course], [name])
VALUES (3, N'test', N'axy')
INSERT INTO [dbo].[student] ([sid], [course], [name])
VALUES (4, N'FE-python-java;base-mysql', N'anr')
基于这些数据,我想要这样的输出:
Sid | course |name
----+-------------------+-----
1 |sql,java |abc
2 |net,oracle,python |xyz
3 | |axy
4 |python,java,mysql |anr
我已经尝试使用这样的 SQL:
select
sid,
substring([course], charindex([course], '-') + 1, len([course])) course,
name
from
student
但是,此查询没有返回预期的结果。
如何在 SQL Server 中编写查询来完成此任务?
I have a question about SQL Server: how to split a string using _
and get required format.
If we do not have - symbol then keep empty value.
Table :
CREATE TABLE [dbo].[student]
(
[sid] [int] NULL,
[course] [varchar](500) NULL,
[name] [varchar](50) NULL
)
INSERT INTO [dbo].[student] ([sid], [course], [name])
VALUES (1, N'database-sql;FE-Java', N'abc')
INSERT INTO [dbo].[student] ([sid], [course], [name])
VALUES (2, N'FE-net;database-oracle;FE-python', N'xyz')
INSERT INTO [dbo].[student] ([sid], [course], [name])
VALUES (3, N'test', N'axy')
INSERT INTO [dbo].[student] ([sid], [course], [name])
VALUES (4, N'FE-python-java;base-mysql', N'anr')
Based on this data, I want output like this:
Sid | course |name
----+-------------------+-----
1 |sql,java |abc
2 |net,oracle,python |xyz
3 | |axy
4 |python,java,mysql |anr
I have tried with SQL like this:
select
sid,
substring([course], charindex([course], '-') + 1, len([course])) course,
name
from
student
This query however is not returning the expected results.
How can I write a query to achieve this task in SQL Server?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
请尝试以下解决方案。
它将从 SQL Server 2016 开始运行。
SQL
输出
Please try the following solution.
It will work starting from SQL Server 2016 onwards.
SQL
Output
使用这个查询:
use this query: