views:

95

answers:

1

I have two tasks and since I am new to it, I need some help/advice from the masters.

What I need to do is send the result of q select query to a csv file which can have delimeter as comma or tab and then send this file as mail to a particular receipient.

Hoping for some great advice

A: 

Try something like that:

DECLARE @cvs nvarchar(MAX)
DECLARE @separator nvarchar(1)

SET @cvs = N''
SET @separator = ','

SELECT TOP 10 
    @cvs = @cvs + CAST(int_column AS nvarchar) + @separator +  nvarchar_column + @separator + CAST(datetime AS nvarchar) + CHAR(13)
FROM
    data_table WITH (NOLOCK)

SELECT @cvs
PRINT @cvs

EXEC msdb.dbo.sp_send_dbmail 
    @recipients = @mail_recipients,
    @profile_name = 'SO',
    @subject = @mail_subject,
    @body = @cvs

Use COALESCE to avoid NULL values, cast columns to nvarchar type if needed.

Grzegorz Gierlik