Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 SQL Server 2005 Forums
 Transact-SQL (2005)
 UDF for ORDER BY

Author  Topic 

ThePrisoner
Starting Member

18 Posts

Posted - 2007-03-28 : 09:00:07
hello

I need a UDF similar to the following

/****** Object: UserDefinedFunction [dbo].[fn_MVParam] Script Date: 03/28/2007 14:46:16 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER FUNCTION [dbo].[fn_MVParam](@RepParam nvarchar(4000), @Delim char(1)= ',')
RETURNS @VALUES TABLE (Parame nvarchar(4000))AS
BEGIN
DECLARE @chrind INT
DECLARE @Piece nvarchar(4000)
SELECT @chrind = 1
WHILE @chrind > 0
BEGIN
SELECT @chrind = CHARINDEX(@Delim,@RepParam)
IF @chrind > 0
SELECT @Piece = LEFT(@RepParam,@chrind - 1)
ELSE
SELECT @Piece = @RepParam
INSERT @VALUES(Parame) VALUES(@Piece)
SELECT @RepParam = RIGHT(@RepParam,LEN(@RepParam) - @chrind)
IF LEN(@RepParam) = 0 BREAK
END
RETURN
END

but I would need it to use in an ORDER BY clause, better explained in this topic
http://www.sqlteam.com/forums/topic.asp?TOPIC_ID=6055

SwePeso
Patron Saint of Lost Yaks

30421 Posts

Posted - 2007-03-28 : 09:12:37
There are many CSV split functions here. Even more efficient.

Add another table variable. Store parts in there. When loop is done, insert from table variable to result table variable, SORTED.


Peter Larsson
Helsingborg, Sweden
Go to Top of Page

ThePrisoner
Starting Member

18 Posts

Posted - 2007-03-28 : 10:05:14
yeah I figured it out by ading an identity column
create FUNCTION [dbo].[fn_MVParamSorted](@RepParam nvarchar(4000), @Delim char(1)= ',')
RETURNS @VALUES TABLE (SortID int identity,Parame nvarchar(4000))AS
BEGIN
DECLARE @chrind INT
DECLARE @Piece nvarchar(4000)
SELECT @chrind = 1
WHILE @chrind > 0
BEGIN
SELECT @chrind = CHARINDEX(@Delim,@RepParam)
IF @chrind > 0
SELECT @Piece = LEFT(@RepParam,@chrind - 1)
ELSE
SELECT @Piece = @RepParam
INSERT @VALUES(Parame) VALUES(@Piece)
SELECT @RepParam = RIGHT(@RepParam,LEN(@RepParam) - @chrind)
IF LEN(@RepParam) = 0 BREAK
END
RETURN
END

then in my query

inner join dbo.fn_MVParamSorted(@stringtoorderby,',')
on foo.product = fn_MVParamSorted.parame
GROUP BY fn_MVParamSorted.parame,fn_MVParamSorted.sortid
order by fn_MVParamSorted.sortid

Go to Top of Page
   

- Advertisement -