Thursday, January 28, 2010

SQL Function to quote for CSV

MSSQL doesn't provide any way to text-qualify fields with quotes for CSV output. The SSIS filters will do this for you, but if you're using BCP or something even more primitive :) it can be a pain.

Use this function to throw double-quotes around text fields if they contain a comma:


ALTER function fn_QuoteCSV
(
@input varchar(4000)
)
RETURNS varchar(4000)
AS
BEGIN
declare @rtn varchar(4000)
select @rtn=@input

IF CHARINDEX(',',@input) > 0
BEGIN
select @rtn = QUOTENAME(@input,CHAR(34))
END

return @rtn

END

No comments: