Possible Duplicate:
Getting error in SQL query with function use
I get this error when attempting to create a function:
'CREATE FUNCTION' must be the first statement in a query batch.
Error:
Incorrect syntax near the keyword 'with'.
If this statement is a common table expression, an xmlnamespaces clause or a change tracking context clause, the previous statement must be terminated with a semicolon. Must declare the scalar variable "@sep".
This is my T-SQL code:
CREATE FUNCTION [dbo].[fn_Split] (@sep nvarchar(10), @s nvarchar(4000))
RETURNS table
AS
RETURN (
WITH Pieces(pn, start, stop) AS (
SELECT 1, 1, CHARINDEX(@sep, @s)
UNION ALL
SELECT pn + 1, stop + (datalength(@sep)/2), CHARINDEX(@sep, @s, stop + (datalength(@sep)/2))
FROM Pieces
WHERE stop > 0
)
SELECT pn,
SUBSTRING(@s, start, CASE WHEN stop > 0 THEN stop-start ELSE 4000 END) AS value
FROM Pieces
)
;