You're trying to do something weird with the declaration of the @Return variable, so the @SQLString is NULL when you run the sp_executesql. You need to declare @Return in the function, so try this instead:set nocount onif not exists (select 'x' where cast(serverproperty('productversion')as varchar(20)) like '8%')beginDECLARE @SQLString nvarchar(1000);if exists (select 'X' from information_schema.routineswhere routine_name = 'xmlassem' androutine_type = 'function')beginSET @SQLString = N'drop function dbo.xmlassem';exec sp_executesql @SQLStringendSET @SQLString=N'CREATE FUNCTION dbo.xmlassem (@taskid INT)RETURNS NVARCHAR(MAX) ASBEGINDECLARE @Return NVARCHAR(MAX);SELECT @Return = coalesce(@Return + '','' + cast(xmldata AS nvarchar(max)) , cast(xmldata AS nvarchar(max)))FROM xmldata_segmentsWHERE eventmgrtaskid = @taskidORDER BY eventmgrtaskid, xmldataidRETURN @ReturnEND'exec sp_executesql @SQLStringendgo