本文介绍了用户定义函数在SQL Server中获取字符串中最长的单词的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在SQL中创建一个UDF来返回字符串中最长的单词。我创建了以下,但我无法让它正常工作。任何建议吗?

$ pre $ CREATE FUNCTION [dbo]。[ufn_Longestword](@input varchar(255))

RETURNS varchar(100)
AS
BEGIN

declare @pos int
declare @ pos2 int
declare @wordpos int
declare @ $ @ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $'$'
$ b SET @pos = 1
WHILE @pos BEGIN
SET @ Letter1 =子串(@input,@pos,1)
IF @ Letter1 =''
BEGIN
SET @ pos2 = @pos
WHILE @ pos2 BEGIN
SET @ Letter2 =子串(@input,@ pos2,1)
if @ letter2 =''
BEGIN
插入@twords
选择SUBSTRING(@input,@ pos,@ pos 2 - @pos)
END
SET @ pos2 = @ pos2 + 1
END

END
SET @pos = @pos + 1
END

SET @longestword =(从@twords选择前1个单词
ORDER BY len(words)desc)

从@twords删除

RETURN @longestword
END

我试图获得不同的在2个空格之间并将该单词插入临时表中,但它不起作用。

解决方案

相反,您可以使用它。 $ b

  DECLARE @str VARCHAR(5000)='aaaa bbbbb cccccccc'

SELECT TOP 1 Split.a.value('。','VARCHAR(100)')as longest_Word
FROM(SELECT Cast('< M>'替换(@str,'','< / M>< M>)+'< / M&
CROSS APPLY Data.nodes('/ M')AS Split(a)
ORDER BY Len(Split.a.value('。','VARCHAR(100)'))DESC

结果 cccccccc


I've trying to create a UDF in SQL to return the longest word in a string. I've created the following but I cant get it to work properly. Any suggestions?

CREATE FUNCTION [dbo].[ufn_Longestword] (@input varchar(255))

RETURNS varchar(100) 
AS
BEGIN 

    declare @pos int
    declare @pos2 int
    declare @wordpos int
    declare @longestword varchar(100)
    declare @Letter1 varchar (1)
    declare @Letter2 varchar (1)
    declare @twords table (
                            words varchar(100))

    SET @pos = 1
    WHILE @pos <= len(@input) 
    BEGIN 
        SET @Letter1 = substring(@input, @pos, 1)
        IF @Letter1 = ' '
        BEGIN
            SET @pos2 = @pos
            WHILE @pos2 <= len(@input)
            BEGIN
                SET @Letter2 = substring(@input, @pos2, 1)
                if @letter2 = ' '
                    BEGIN 
                        insert into @twords
                        select SUBSTRING(@input, @pos,@pos2 - @pos)
                    END
            SET @pos2 = @pos2 + 1
            END

        END
        SET @pos = @pos + 1
    END

    SET @longestword = (select top 1 words from @twords 
                        ORDER BY len(words)desc)

    delete from @twords

RETURN @longestword
END

I#m trying to get the different between the 2 spaces and insert that word into a temp table but it doesnt work.

解决方案

Instead you can use this.

DECLARE @str VARCHAR(5000)='aaaa bbbbb cccccccc'

SELECT TOP 1 Split.a.value('.', 'VARCHAR(100)') as longest_Word
FROM   (SELECT Cast ('<M>' + Replace(@str, ' ', '</M><M>') + '</M>' AS XML) AS Data) AS A
       CROSS APPLY Data.nodes ('/M') AS Split(a)
ORDER  BY Len(Split.a.value('.', 'VARCHAR(100)')) DESC 

Result : cccccccc

这篇关于用户定义函数在SQL Server中获取字符串中最长的单词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-27 07:08