DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Snippets has posted 5883 posts at DZone. View Full User Profile

Add Variant To List

  • submit to reddit
        If both element and list are nvarchars, using <a href="">dbo.fnAddToList</a> will be faster

Oskar Austegard
<a href=""></a>
--Adds a sql_variant element to the end of a sql_variant list, after first inserting a delimiter (nvarchar)
--If both element and list are nvarchars, using dbo.fnAddToList will be faster
ALTER FUNCTION dbo.fnAddVarToList (@VarList sql_variant, @VarNew sql_variant, @Del nvarchar(10))
RETURNS nvarchar(4000)
	DECLARE @List nvarchar(4000), @New nvarchar(4000)
	SELECT @List = NULLIF(CONVERT(nvarchar(4000), @VarList), ''), 
		@New = NULLIF(CONVERT(nvarchar(4000), @VarNew), '')
  --First try the concatened string, if null then just the list, 
	--if it too is null, just the new element
	RETURN COALESCE(@List + @Del + @New, @List, @New)