【发布时间】:2014-08-28 23:46:30
【问题描述】:
我一直在寻找答案,但我似乎找不到任何指向正确方向的东西。
我需要创建一个 UDF,它将提取文本字符串的每个单词并返回一个表格,其中字符串的每个单词位于单独的行中。
UDF 只能接受一个变量“@mytext”。
我们可以假设文本字符串由一个空格分隔,并且可能包含逗号或句点。
例如,“不要担心失败,担心你甚至不尝试就错过的机会。”将需要返回一个表格,其中每个单词位于列的单独行上,不存在逗号或句点。
我认为文本字符串需要用一个通用值分隔,该值可用于分隔每个单词以进行插入,但我可能完全错了。
对此的任何帮助将不胜感激!
根据我到目前为止所说的,这是我不太确定如何继续的完整代码
create function [dbo].[textConverter]
(
@mytext nvarchar(max)
)
returns @text_string table
(
word nvarchar
)
as
begin
set @mytext = replace(@mytext, 'what needs to be changed', 'what it needs to be changed too')
--insert string to table
end
编辑
我检查了几个链接并发现了更多关于此的信息,我现在得到了这段代码。但是它退出并出现错误。文章中使用的示例我在插入中找到了已使用数字的代码,所以这可能是问题所在??
create function [dbo].[textConverter]
(
@mytext varchar(max)
)
returns @text_string table
(
word nvarchar
)
as
begin
--Change string to be seperated by commas
set @mytext = replace(@mytext, ' ', ',')
set @mytext = replace(@mytext, '.',',')
--Eliminate double commas
set @mytext = replace(@mytext, ',,', ',')
declare @name nvarchar(255)
declare @pos int
while CHARINDEX(',', @mytext) > 0
begin
select @pos = CHARINDEX(',', @mytext)
select @name = SUBSTRING(@mytext, 1, @pos-1)
insert into @text_string
select @name
select @mytext = SUBSTRING(@mytext, @pos+1, LEN(@mytext)-@pos)
end
insert into @text_string
select @mytext
return
end
--To use function
select * from dbo.textConverter('don’t worry about failures, worry about the chances you miss when you don’t even try.')
【问题讨论】:
-
什么关系型数据库?你的语法看起来像 SQL-Server。
-
@Barmar 对不起,我应该提到的。是的,它是 SQL-Server
标签: sql sql-server tsql user-defined-functions