SQL Server 2008 alternative for SQL-DMO - sql

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

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

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

sp_OAMethod 'DeleteFile' Method not working in SQL Server 2008 R2

I have an sql stored procedure that I use to delete files from the windows file system using the sp_OAMethod. This used to work fine when we were using sql server 2005, however, it does not work at all now when using sql server 2008 R2. I have read that you can use SQLDMO/SQLCLR however, I cannot find any decent information regarding these methods. My previous code is below:
-- declare variables
declare #ObjectID nvarchar(10),
#ObjectType nvarchar(255),
#BackupName nvarchar(255),
#BackupLocation nvarchar(255),
#ExpiryDate datetime,
#DeletedStatus bit,
#SQL nvarchar(4000),
#SQL1 nvarchar(4000),
#SQL2 nvarchar(4000),
#Result int,
#FSO_Token int,
#FileLocation nvarchar(4000)
-- declare cursor for table backups
declare backupexpired_cursor cursor for
select dbo.tbl_BackupObjects.ObjectID, dbo.tbl_BackupObjects.ObjectType, dbo.tbl_BackupObjects.BackupName,
dbo.tbl_BackupObjects.BackupLocation, dbo.tbl_BackupObjects.ExpiryDate, dbo.tbl_BackupObjects.Deleted
from dbo.tbl_BackupObjects
where dbo.tbl_BackupObjects.Deleted <> 1
-- open cursor
open backupexpired_cursor
-- fetch the next record from the cursor
fetch next from backupexpired_cursor into #ObjectID, #ObjectType, #BackupName, #BackupLocation, #ExpiryDate, #DeletedStatus
while (##FETCH_STATUS <> -1)
begin
if (##FETCH_STATUS <> -2)
begin
if (#ExpiryDate < GetDate())
begin
if (#ObjectType = 'Table')
begin
begin try
begin transaction
-- Only done if the object type is a table object
-- Remove old backup
select #SQL = 'drop table dbo.' + quotename(#BackupName)
exec sp_executesql #SQL
-- update the deleted status and the date deleted of the deleted object
select #SQL1 = 'update tbl_BackupObjects
set Deleted = 1,
DeletedDate = GetDate()
where ObjectID = ''' + #ObjectID + ''''
exec sp_executesql #SQL1
commit transaction
end try
begin catch
rollback transaction
select #SQL1 = 'update tbl_BackupObjects
set Deleted = 0,
DeletedDate = NULL
where ObjectID = ''' + #ObjectID + ''''
exec sp_executesql #SQL1
end catch
end
else
begin
begin try
begin transaction
-- Only done if the object(view, stored procedure, and/or function is saved
-- in a file located on the windows file system.
-- Create File Location
set #FileLocation = 'G:\Backup Registry Script Files\' + #BackupLocation + '\' + #BackupName + ''
-- Create a token of the object
EXEC #Result = sp_OACreate 'Scripting.FileSystemObject', #FSO_Token OUTPUT
-- Call the deletefile method using the #FileLocation parameter and the token created above:
-- - The object token created by sp_OACreate
-- - The method name
-- - The method's return value
-- - Parameters that will be used by the object method
EXEC #Result = sp_OAMethod #FSO_Token, 'DeleteFile', NULL, #FileLocation
-- Execute ole method
EXEC #Result = sp_OADestroy #FSO_Token
-- update the deleted status and the date deleted of the deleted object
select #SQL1 = 'update tbl_BackupObjects
set Deleted = 1,
DeletedDate = GetDate()
where ObjectID = ''' + #ObjectID + ''''
exec sp_executesql #SQL1
commit transaction
end try
begin catch
rollback transaction
select #SQL1 = 'update tbl_BackupObjects
set Deleted = 0,
DeletedDate = GetDate()
where ObjectID = ''' + #ObjectID + ''''
exec sp_executesql #SQL1
end catch
end
end
end
-- fetch the next record from the cursor
fetch next from backupexpired_cursor into #ObjectID, #ObjectType, #BackupName, #BackupLocation, #ExpiryDate, #DeletedStatus
end
-- set the Last and Next Removal Dates
select #SQL2 = 'update tbl_BackupRemovalDate
set LastRemovalDate = GetDate(),
NextRemovalDate = GetDate() + 7'
exec sp_executesql #SQL2
-- close cursor
close backupexpired_cursor
deallocate backupexpired_cursor
I have seen that SQLDMO is quite similar to what I have, however I cannot find any information on how to delete a file system file using this method. Can anyone help?
Do you have Enable Ole Automation Procedures feature ?
try this
EXEC sp_configure 'show advanced options', 1
RECONFIGURE
EXEC sp_configure 'Ole Automation Procedures', 1
RECONFIGURE

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)

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

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