如何从 SQL 存储过程中打印文档
使用 SQL OLE 和 VB DLL 从存储过程中打印文档。
引言
有很多不同的方法可以从数据库中提取数据,然后根据您的需要对其进行格式化/打印。 以下代码允许您使用 SQL OLE 和 VB DLL 从存储过程打印文档。 原始文章可以在Siccolo 文章存档中找到。
步骤 1
首先,让我们构建一个简单的 VB DLL(ActiveX 组件),它将使用 Microsoft Word 处理实际的打印。

在 ActiveX 组件中,添加一个使用 Microsoft Word 打印文档的方法
Public Sub PrintDocumentFromWord(ByVal DocumentFileName As String)
On Error GoTo Err_Error
Dim MethodName As String
MethodName = ".PrintWebDocumentFromWord()"
Dim strMessage As String
Dim blnResult As Boolean
Dim objWord As New Word.Application
'Dim objWord As Object
'Set objWord = CreateObject("Word.Application")
Const wdAlertsNone = 0
objWord.DisplayAlerts = wdAlertsNone
'objWord.Activate
'objWord.PrintOut FileName:=DocumentFileName
Dim objDocument As Word.Document
Set objDocument = objWord.Documents.Open(DocumentFileName)
objDocument.Activate
objDocument.PrintOut
objDocument.Close
objWord.Quit
Exit_Procedure:
Set objDocument = Nothing
Set objWord = Nothing
Exit Sub
Err_Error:
'handle error here
Call HandleError("PrintWebDocument", ApplicationName, MethodName, VBA.Error)
If Not objWord Is Nothing Then
objWord.Quit
End If
Resume Exit_Procedure
End Sub
编译并构建 ActiveX 组件。 ActiveX 组件将驻留在运行 SQL Server 实例的同一机器上。
第二步
接下来,创建一个存储过程,该过程调用 ActiveX 组件并将要打印的文档的文件名传递给它
CREATE procedure sp_Print_Letter_File
(
@file_name varchar(333)
,@debug_mode char(1)=''
)
as
set nocount on
declare @return int
declare @print_document int
declare @hr int
declare @src varchar(255), @desc varchar(255)
exec @hr = master.dbo.sp_OACreate 'PrintDocument.clsPrintDocument', _
@print_document OUT
if @hr <> 0 -- error creating instance!
begin
exec master.dbo.sp_OAGetErrorInfo @print_document, @src out, @desc out
select 'Creating Instance', hr=convert(varbinary(4),@hr), _
source=@src, description=@desc
set @return = -1
goto error
end
if @debug_mode<>''
print '1. created'
exec @hr = sp_OAMethod @print_document, 'PrintDocumentFromWord',_
null,@file_name, @debug_mode
if @hr <> 0
begin
exec sp_OAGetErrorInfo @print_document, @src OUT, @desc OUT
select 'Call to Method', hr=convert(varbinary(4),@hr), _
Source=@src, Description=@desc
exec @hr = sp_OADestroy @print_document
if @hr <> 0
begin
exec sp_OAGetErrorInfo @print_document, @src out, @desc out
select 'Destroing Instance',hr=convert(varbinary(4),@hr), _
source=@src, description=@desc
--return
end
set @return = -2
goto error
end
if @debug_mode<>''
print '2. send to object'
error:
exec @hr = sp_OADestroy @print_document
if @hr <> 0
begin
exec sp_OAGetErrorInfo @print_document, @src out, @desc out
select 'Destroing Instance',hr=convert(varbinary(4),@hr), _
source=@src, description=@desc
set @return = -3
end
if @debug_mode<>''
print '3. done!'
set nocount off
GO
就这样。 不要忘记注册您的 ActiveX 组件(我通常使用组件服务 MMC 管理单元来执行此操作)。
如果您想了解更多关于这个故事的信息 - 请查看 Siccolo - SQL Server 免费移动管理工具 以及更多文章在 Siccolo 文章。
历史
- 2007 年 2 月 6 日:初始发布