How to attach a file to an email using SQL stored procedure? - sql

Can't seem to find much information about how to attach a file that's been stored as a BLOB as part of an email.
I know you can attach files from the file system (C:\temp...) to email that are being setup in DBMAIL or custom stored procedures. However, I haven't seen any references to attaching something such as a PDF that's been stored as a binary object in a table.
I see where you can attach a query as a file, but I don't think that's what I'm looking for.
We would do this programatically via the application, but we need to be able to kick this SP via triggers or the application's server side code.
Is this possible or should i be asking other questions, since usually a binary object also needs to have a content type associated with it for browsers or mail objects to know how to handle?

The solution can not attach binary object stored in db field, you may change your schema a little bit store the path to the binary file. if you could enable .net clr in your database server, you will have more options.
use master
go
if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[usp_send_cdosysmail]')
and objectproperty(id, N'isprocedure') = 1)
drop procedure [dbo].[usp_send_cdosysmail]
go
create procedure usp_send_cdosysmail
#from varchar(500) ,
#to varchar(500) ,
#subject varchar(500),
#body nvarchar(max) ,
#smtpserver varchar(25),
#bodytype varchar(10) ,
#attachment varchar(100)= ' '
as
declare #imsg int
declare #hr int
declare #source varchar(255)
declare #description varchar(500)
declare #output varchar(1000)
exec #hr = sp_oacreate 'cdo.message', #imsg out
exec #hr = sp_oasetproperty #imsg,
'configuration.fields("http://schemas.microsoft.com/cdo/configuration/sendusing").value','2'
exec #hr = sp_oasetproperty #imsg, 'configuration.fields("http://schemas.microsoft.com/cdo/configuration/smtpserver").value', #smtpserver
exec #hr = sp_oamethod #imsg, 'configuration.fields.update', null
exec #hr = sp_oasetproperty #imsg, 'to', #to
exec #hr = sp_oasetproperty #imsg, 'from', #from
exec #hr = sp_oasetproperty #imsg, 'subject', #subject
-- if you are using html e-mail, use 'htmlbody' instead of 'textbody'.
exec #hr = sp_oasetproperty #imsg, #bodytype, #body
-- Attachments...
IF #attachment IS NOT NULL AND LEN(#attachment) > 0 BEGIN
Declare #files table(fileid int identity(1,1),[file] varchar(255))
Declare #file varchar(255)
Declare #filecount int ; set #filecount=0
Declare #counter int ; set #counter = 1
DECLARE #outVar INT
SET #outVar = NULL
INSERT #files SELECT cValue FROM master..fn_split(#attachment,',')
SELECT #filecount=##ROWCOUNT
WHILE #counter<(#filecount+1)
BEGIN
SELECT #file = [file]
FROM #files
WHERE fileid=#counter
EXEC #hr = sp_OAMethod #imsg, 'AddAttachment',#outVar OUT, #file
SET #counter=#counter+1
END
END
exec #hr = sp_oamethod #imsg, 'send', null
-- sample error handling.
if #hr <>0
select #hr
begin
exec #hr = sp_oageterrorinfo null, #source out, #description out
if #hr = 0
begin
select #output = ' source: ' + #source
print #output
select #output = ' description: ' + #description
print #output
end
else
begin
print ' sp_oageterrorinfo failed.'
return
end
end
exec #hr = sp_oadestroy #imsg
go
set quoted_identifier off
go
set ansi_nulls on
go
sp_configure 'Ole Automation Procedures', 1
RECONFIGURE
GO

Related

Saving the BLOB data to a file via OLE processes

I am trying to export data from SQL Server to a file. The data is a .jpg. I found a script that would do so however whenever i run it I get a not any error message. and file not create in folder Please help me
DECLARE xArgsEntryImg CURSOR FOR
SELECT TOP 1
CONVERT(varbinary(max), E.ENTRY_IMAGE, 1) AS img1,
CONVERT(varchar(50), E.TKT_NO) + 'IMG1.jpg' AS img,
T.TicketNo
FROM
ITNLTCS_IMAGE.dbo.ICS_ENTRY_IMAGE E
INNER JOIN
fms25.dbo.tblTagTransaction T ON E.TKT_NO = T.TicketNo
INNER JOIN
FMS25.dbo.ReqPayViolationMessage m ON (T.TagTransactionPk = m.TagTransactionPk)
WHERE
NOT EXISTS (SELECT TOP 1 1
FROM tblImgUploadLog I
WHERE ImgType = 1
AND T.TicketNo = I.TicketNo)
DECLARE #PathForEntryImg nvarchar(max);
DECLARE #ImageDataForEntryImg varbinary(max);
DECLARE #FilenameForEntryImg NVARCHAR(max);
DECLARE #TicketNoForEntryImg bigint;
OPEN xArgsEntryImg
FETCH xArgsEntryImg INTO #ImageDataForEntryImg, #FilenameForEntryImg, #TicketNoForEntryImg
WHILE ##FETCH_STATUS = 0
BEGIN
BEGIN TRY
DECLARE #FullPathToOutputFileforEntryImg NVARCHAR(max);
DECLARE #FileName varchar(4000) = 'D:\FMS\IMAGES\CURRENT\a.jpg'
DECLARE #ObjectTokenEntryImg INT
EXEC sp_OACreate 'ADODB.Stream', #ObjectTokenEntryImg OUTPUT; -- Create Object
EXEC sp_OASetProperty #ObjectTokenEntryImg, 'Type', 1;
EXEC sp_OAMethod #ObjectTokenEntryImg, 'Open';
EXEC sp_OAMethod #ObjectTokenEntryImg, 'Write', NULL, #ImageDataForEntryImg;
EXEC sp_OAMethod #ObjectTokenEntryImg, 'SaveToFile', NULL, #FileName, 2;
EXEC sp_OAMethod #ObjectTokenEntryImg, 'Close';
EXEC sp_OADestroy #ObjectTokenEntryImg;
END TRY
BEGIN CATCH
END CATCH
FETCH NEXT From xArgsEntryImg INTO #ImageDataForEntryImg, #FilenameForEntryImg, #TicketNoForEntryImg
END
CLOSE xArgsEntryImg
DEALLOCATE xArgsEntryImg

SQL Server Export Blob Corrupts All Files

I am exporting blobs with this code:
sp_configure 'Ole Automation Procedures', 1;
GO
RECONFIGURE;
GO
DECLARE #outout_path varchar(50) = 'D:\blob',
#i bigint,
#init int,
#data varbinary(max),
#file_path varchar(max),
#folder_path varchar(max)
DECLARE #Doctable TABLE (id int identity(1,1) , [FileName] varchar(100), file_data varBinary(max) )
INSERT INTO #Doctable([FileName],file_data)
Select top 10 thefilename, file_data FROM schm.table_with_blobs
SELECT #i = COUNT(1) FROM #Doctable
WHILE #i >= 1
BEGIN
SELECT #data = [file_data],
#file_path = #outout_path + '\'+ cast(id as varchar) + '\' + [FileName],
#folder_path = #outout_path + '\'+ cast(id as varchar)
FROM #Doctable
WHERE id = #i
EXEC [dbo].[CreateFolder] #folder_path
EXEC sp_OACreate 'ADODB.Stream', #init OUTPUT;
EXEC sp_OASetProperty #init, 'Type', 1;
EXEC sp_OAMethod #init, 'Open';
EXEC sp_OAMethod #init, 'Write', NULL, #data;
EXEC sp_OAMethod #init, 'SaveToFile', NULL, #file_path, 2;
EXEC sp_OAMethod #init, 'Close';
EXEC sp_OADestroy #init;
print 'Document Generated at - '+ #file_path
SELECT #data = NULL,
#init = NULL,
#file_path = NULL,
#folder_path = NULL;
SET #i -= 1;
END
All the files are exported as expected with the proper file format. However, all of the files are corrupted and cannot be opened, regardless of file format. What can I tweak to avoid this? Do I need to more explicitly call out the file type (available in thefilename field)?
I had a similar problem but was exporting with BCP rather than using ADODB.
I had to do two things :
convert the varbinary to varchar or nvarchar
make BCP export as
RAW
This is the BCP solution I came up with:
Declare #patient int, #mincount int, #maxcount int,#filename varchar(200), #script varchar(2000),#fileid varchar(10)
Set #patient=2;
set #mincount=1;
Declare #mydocs as table
(filename varchar(255), filebody image, drank int, file_id int)
insert into #mydocs
Select taf.Attachment_File_Name, taf.Attachment_File_Body, DENSE_RANK() OVER (ORDER BY taf.attachment_file_id) as drank, taf.Attachment_File_ID FROM [CNGSTT].[dbo].[tblAttachment] ta
left join [CNGSTT].[dbo].[tblAttachmentFile] taf
on taf.Attachment_ID=ta.Attachment_ID where ta.Patient_ID=#patient
Set #maxcount=(select MAX(drank) from #mydocs)
WHILE #mincount<=#maxcount
BEGIN
Set #filename = (select fle.FileName from #mydocs fle where drank=#mincount)
Set #fileid =(select fle.File_id from #mydocs fle where drank=#mincount)
set #script = 'bcp "SELECT cast(cast(Attachment_File_Body as varbinary(max)) as varchar(max)) from [tblattachmentfile] fle where Attachment_File_ID='+#fileid+'" queryout D:\temp\' + #filename + ' -T -c -C RAW'
exec master..xp_cmdshell #script
Set #mincount=#mincount+1
END

Export multiple images from image column

I have the following stored procedure, how could I modify it to export multiple images at once? A TicketID can contain several images, could the IN statement work here? Appreciate all answers!
CREATE PROCEDURE dbo.ExportImage (
#ImgName NVARCHAR (100)
,#ImageFolderPath NVARCHAR(1000)
,#Filename NVARCHAR(1000)
)
AS
BEGIN
DECLARE #ImageData VARBINARY (max);
DECLARE #Path2OutFile NVARCHAR (2000);
DECLARE #Obj INT
SET NOCOUNT ON
SELECT #ImageData = (
SELECT convert (VARBINARY (max), ImgData, 1)
FROM Images
WHERE TicketID = #ImgName
);
SET #Path2OutFile = CONCAT (
#ImageFolderPath
,'\'
, #Filename
);
BEGIN TRY
EXEC sp_OACreate 'ADODB.Stream' ,#Obj OUTPUT;
EXEC sp_OASetProperty #Obj ,'Type',1;
EXEC sp_OAMethod #Obj,'Open';
EXEC sp_OAMethod #Obj,'Write', NULL, #ImageData;
EXEC sp_OAMethod #Obj,'SaveToFile', NULL, #Path2OutFile, 2;
EXEC sp_OAMethod #Obj,'Close';
EXEC sp_OADestroy #Obj;
END TRY
BEGIN CATCH
EXEC sp_OADestroy #Obj;
END CATCH
SET NOCOUNT OFF
END
This is the query I execute:
exec dbo.ExportImage '2042','C:\ExpImg','2042.jpg'
Errormsg:
Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <=, >, >= or when the subquery is used as an expression.
Something like that:
CREATE PROCEDURE dbo.ExportImage (
#ImgName NVARCHAR (100)
,#ImageFolderPath NVARCHAR(1000)
,#Filename NVARCHAR(1000)
)
AS
BEGIN
DECLARE #ImageData VARBINARY (max);
DECLARE #Path2OutFile NVARCHAR (2000);
DECLARE #Obj INT
SET NOCOUNT ON
DECLARE #cursor CURSOR
SET #cursor = CURSOR FOR
SELECT convert (VARBINARY (max), ImgData, 1)
FROM Images
WHERE TicketID = #ImgName
OPEN #cursor
FETCH NEXT
FROM #cursor INTO #ImageData
WHILE ##FETCH_STATUS = 0
BEGIN
SET #Path2OutFile = CONCAT (
#ImageFolderPath
,'\'
, #Filename
);
BEGIN TRY
EXEC sp_OACreate 'ADODB.Stream' ,#Obj OUTPUT;
EXEC sp_OASetProperty #Obj ,'Type',1;
EXEC sp_OAMethod #Obj,'Open';
EXEC sp_OAMethod #Obj,'Write', NULL, #ImageData;
EXEC sp_OAMethod #Obj,'SaveToFile', NULL, #Path2OutFile, 2;
EXEC sp_OAMethod #Obj,'Close';
EXEC sp_OADestroy #Obj;
END TRY
BEGIN CATCH
EXEC sp_OADestroy #Obj;
END CATCH
FETCH NEXT
FROM #cursor INTO #ImageData
END
CLOSE #cursor
DEALLOCATE #cursor
END

sql server - Google maps api returns too much data

Im using sql server to call out to the google maps api and get data for a gps location. It worked fine but lately my stored procedure that calls out fails with this error
0x8004271F
ODSOLE Extended Procedure
The source data specified for this string or binary column or parameter is too long.
It seems that the character limit is being reached when google returns a "boat load" of location data.
This is what Im calling out with so far:
-- Select dbo.fnGetAddressFromGPS('33.83528299,-118.28754585')
-- -- GO
Declare #GPS VarChar(50)
Set #GPS = '34.55,-118.50'
DECLARE #URL VarChar(4000)
DECLARE #win int
DECLARE #hr int
DECLARE #text varchar(8000)
Set #URL = 'http://maps.googleapis.com/maps/api/geocode/xml?latlng=' + #GPS + '&sensor=false'
Set #URL = 'http://maps.googleapis.com/maps/api/geocode/xml?latlng=34.5566767,-118.50677688&sensor=false'
Set #URL = 'http://maps.googleapis.com/maps/api/geocode/json? latlng=34.5566767,-118.50677688&sensor=false'
EXEC #hr=sp_OACreate 'WinHttp.WinHttpRequest.5.1',#win OUT
IF #hr <> 0 EXEC sp_OAGetErrorInfo #win
EXEC #hr=sp_OAMethod #win, 'Open',NULL,'GET',#url,'false'
IF #hr <> 0 EXEC sp_OAGetErrorInfo #win
EXEC #hr=sp_OAMethod #win,'Send'
IF #hr <> 0 EXEC sp_OAGetErrorInfo #win
EXEC #hr=sp_OAGetProperty #win, 'ResponseText',#text OUTPUT
IF #hr <> 0 EXEC sp_OAGetErrorInfo #win
EXEC #hr=sp_OADestroy #win
--IF #hr <> 0 EXEC sp_OAGetErrorInfo #win
Select #Text As 'GoogleResult'
Return
IF CHARINDEX('ZERO_RESULTS', #text) > 0
Select 'No Address Found'
Declare #i Int
Declare #j Int
Declare #Address VarChar(150)
SELECT #i = CHARINDEX('<formatted_address>', #Text);
SELECT #j = CHARINDEX('</formatted_address>', #Text);
SELECT #i = CHARINDEX('"formatted_address" : "', #Text);
Select #i
Return
If #j-#i-Len('<formatted_address>') <= 0
Select #Address = 'N/A'
Else
Select #Address = SubString(#text, #i+Len('<formatted_address>'), #j-#i- Len('<formatted_address>'))
--Select #Address
Select #Address
What I would like to do is limit the returning data from google to only the formatted address portion which is all I really need but I havent found anywhere in the documenation on how to do such a thing. The only other thing I can think of doing is truncating the result data but I cant figure that out either at the moment. Any help would be much appreciated.
The interesting part here is inserting into a table:
DECLARE #resTbl AS TABLE (result NVARCHAR(MAX))
INSERT #resTbl EXEC #HttpWinRequest=sp_OAGetProperty #win, 'ResponseText'
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE dbo.usp_http_get
/*
sp_configure 'show advanced options', 1;
GO
RECONFIGURE;
GO
sp_configure 'Ole Automation Procedures', 1;
GO
RECONFIGURE;
GO
*/
#url VARCHAR(8000)
AS
BEGIN
SET NOCOUNT ON;
DECLARE #win int, #HttpWinRequest int
DECLARE #resTbl AS TABLE (result NVARCHAR(MAX))
EXEC #HttpWinRequest=sp_OACreate 'WinHttp.WinHttpRequest.5.1',#win OUT
IF #HttpWinRequest <> 0 EXEC sp_OAGetErrorInfo #win
EXEC #HttpWinRequest=sp_OAMethod #win, 'Open',NULL,'GET',#url,'false'
IF #HttpWinRequest <> 0 EXEC sp_OAGetErrorInfo #win EXEC #HttpWinRequest=sp_OAMethod #win,'Send'
IF #HttpWinRequest <> 0 EXEC sp_OAGetErrorInfo #win
INSERT #resTbl EXEC #HttpWinRequest=sp_OAGetProperty #win, 'ResponseText'
IF #HttpWinRequest <> 0 EXEC sp_OAGetErrorInfo #win
EXEC #HttpWinRequest=sp_OADestroy #win
IF #HttpWinRequest <> 0 EXEC sp_OAGetErrorInfo #win
SELECT * FROM #resTbl
END
GO
EXEC usp_http_get #url = 'http://www.yahoo.com' -- varchar(8000)

SQL Server 2008 alternative for SQL-DMO

I previously was using SQL-DMO to automatically generate scripts from the database.
Now I upgraded to SQL Server 2008 and I don’t want to use this feature anymore since Microsoft will be dropping this feature off.
Is there any other alternative I can use to connect to a server and generate scripts automatically from a database?
Any answer is welcome. Thanks in advance.
This is the procedure i was previously using:
CREATE PROC GenerateSP (
#server varchar(30) = null,
#uname varchar(30) = null,
#pwd varchar(30) = null,
#dbname varchar(30) = null,
#filename varchar(200) = 'c:\script.sql'
)
AS
DECLARE #object int
DECLARE #hr int
DECLARE #return varchar(200)
DECLARE #exec_str varchar(2000)
DECLARE #spname sysname
SET NOCOUNT ON
-- Sets the server to the local server
IF #server is NULL
SELECT #server = ##servername
-- Sets the database to the current database
IF #dbname is NULL
SELECT #dbname = db_name()
-- Sets the username to the current user name
IF #uname is NULL
SELECT #uname = SYSTEM_USER
-- Create an object that points to the SQL Server
EXEC #hr = sp_OACreate 'SQLDMO.SQLServer', #object OUT
IF #hr <> 0
BEGIN
PRINT 'error create SQLOLE.SQLServer'
RETURN
END
-- Connect to the SQL Server
IF #pwd is NULL
BEGIN
EXEC #hr = sp_OAMethod #object, 'Connect', NULL, #server, #uname
IF #hr <> 0
BEGIN
PRINT 'error Connect'
RETURN
END
END
ELSE
BEGIN
EXEC #hr = sp_OAMethod #object, 'Connect', NULL, #server, #uname, #pwd
IF #hr <> 0
BEGIN
PRINT 'error Connect'
RETURN
END
END
--Verify the connection
EXEC #hr = sp_OAMethod #object, 'VerifyConnection', #return OUT
IF #hr <> 0
BEGIN
PRINT 'error VerifyConnection'
RETURN
END
SET #exec_str = 'DECLARE script_cursor CURSOR FOR SELECT name FROM ' + #dbname + '..sysobjects WHERE type = ''P'' ORDER BY Name'
EXEC (#exec_str)
OPEN script_cursor
FETCH NEXT FROM script_cursor INTO #spname
WHILE (##fetch_status <> -1)
BEGIN
SET #exec_str = 'Databases("'+ #dbname +'").StoredProcedures("'+RTRIM(UPPER(#spname))+'").Script(74077,"'+ #filename +'")'
EXEC #hr = sp_OAMethod #object, #exec_str, #return OUT
IF #hr <> 0
BEGIN
PRINT 'error Script'
RETURN
END
FETCH NEXT FROM script_cursor INTO #spname
END
CLOSE script_cursor
DEALLOCATE script_cursor
-- Destroy the object
EXEC #hr = sp_OADestroy #object
IF #hr <> 0
BEGIN
PRINT 'error destroy object'
RETURN
END
GO
Download the SQLServer2005_BC.msi from
http://www.microsoft.com/en-us/download/details.aspx?id=24793
then install DMO, also works with 2008/R2!
Are you aware that DMO has been replaced with SMO? Microsoft has no plans to discontinue this, that I'm aware of.
I would suggest you try SQL CRL Stored Procedure. See http://www.sqlteam.com/article/writing-clr-stored-procedures-in-charp-introduction-to-charp-part-1