I have the following UDF.
CREATE FUNCTION [dbo].[udf_GenerateVarcharTableFromStringList]
(@list varchar(MAX),
@delimiter char(1) = N',')
RETURNS @tbl TABLE ([Value] varchar(200))
WITH SCHEMABINDING
AS
BEGIN
DECLARE @chrind INT
DECLARE @Piece nvarchar(4000)
SELECT @chrind = 1
WHILE @chrind > 0
BEGIN
SELECT @chrind = CHARINDEX(@delimiter,@list)
IF @chrind > 0
SELECT @Piece = LEFT(@list,@chrind - 1)
ELSE
SELECT @Piece = @list
INSERT @tbl([Value]) VALUES(@Piece)
SELECT @list = RIGHT(@list,LEN(@list) - @chrind)
IF LEN(@list) = 0 BREAK
END
RETURN
END
I call this function with the following code example from a where clause in my sprocs:
WHERE u.[Owner] IN
(SELECT [VALUE]
FROM dbo.udf_GenerateVarcharTableFromStringList(@Owners, ','))
I use this where statement in sprocs that I use for reporting services multivalue parameters. When a us开发者_如何学Goer selects just blank for the value it returns the correct data but if a user selects a blank value and another value that actually has text it does not return the blank value owners anymore, just the owners from the text? Any ideas? I take it something is wrong with the function?
Well, from what I could gather from your comments it seems that you need a new splitting function. Here's what I use:
create FUNCTION [dbo].[fnSplitString] (@s varchar(512),@sep char(1))
RETURNS table
AS
RETURN (
WITH Pieces(pn, start, stop) AS (
SELECT 1, 1, CHARINDEX(@sep, @s)
UNION ALL
SELECT pn + 1, stop + 1, CHARINDEX(@sep, @s, stop + 1)
FROM Pieces
WHERE stop > 0
)
SELECT pn,
SUBSTRING(@s, start, CASE WHEN stop > 0 THEN stop-start ELSE 512 END) AS s
FROM Pieces
)
It has a nice enumeration feature to it and it doesn't eat blanks. :)
精彩评论