SQL Server 2000: how to save an Image variable to a file in the file system from a stored procedure

安稳与你 提交于 2019-12-04 06:10:05

问题


I have a stored procedure that receives a @Data image parameter.

And I want to save it to the file system from a stored procedure.

Any idea how to do it?


回答1:


You can use OLE automation (ADODB.Stream) to write binary data from a SQL Server 2000 stored procedure, as described here and here. The sample below uses a varbinary variable, but it should work similarly with your image parameter.

DECLARE @Path VarChar(255)
DECLARE @Data VarBinary(1000)
SET @Data = 0x12345678
SET @Path = 'c:\test.dat'

DECLARE @object Integer
DECLARE @hr Integer
-- create the ADO stream object
EXEC @hr = sp_oacreate 'ADODB.Stream', @object OUTPUT, 1
IF (@hr <> 0)
   RAISERROR('ADO stream creation failed', 11, 0)
-- configure it for binary access
EXEC @hr = sp_oasetproperty @object, 'Type', 1
IF (@hr <> 0)
   RAISERROR('Failed to set stream type', 11, 0)
-- open the stream
EXEC @hr = sp_oamethod @object, 'Open'
IF (@hr <> 0)
   RAISERROR('Failed to open the stream object', 11, 0)
-- write the buffer to the stream
EXEC @hr = sp_oamethod @object, 'Write', NULL, @Data
IF (@hr <> 0)
   RAISERROR('Failed to write a buffer to the stream', 11, 0)
-- save the stream to a file with overwrite
EXEC @hr = sp_oamethod @object, 'SaveToFile', NULL, @Path, 2
IF (@hr <> 0)
   RAISERROR('Failed to save the stream to a file', 11, 0)
-- cleanup
EXEC sp_oadestroy @object

Note that access to the file system via this method (and all others in SQL2000 that I know) will occur under the security context of the SQL Server process, not the caller of the stored procedure.

If you aren't comfortable loading the ADO components into your SQL Server process, you could look into implementing an extended stored procedure to write your files.



来源:https://stackoverflow.com/questions/8393564/sql-server-2000-how-to-save-an-image-variable-to-a-file-in-the-file-system-from

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!