我在 Excel 2007 中有一个用户表单,它使用存储过程将数据写入 SQL Server 2008 上的表中。
然后插入的行得到一个我报告给 VBA 的身份。然后我使用这个数字将几行数据填充到另一个表中。
但是,我不想让存储过程先执行然后写入另一个表,而是让存储过程做这两件事。
问题是,另一个表的条目大于一行,我从 VBA 发送到 SQL 的参数只能包含一个值。
所以,我相信我需要在 SQL 中创建一个表变量。但是,如何将 VBA 中的值传递给 SQL 中的表变量?请记住,一切都应该在一个存储过程中完成。这就是我到目前为止所拥有的。
谢谢你的帮助!!!
--SQL Stored Procedure
ALTER procedure [dbo].[Audit_InsertAuditFinding]
@AuditRID as int
,@EnteredBy as varchar(10)
,@AuditItemNumber as int
,@AuditFindingShort as varchar(50)
,@AuditFindingLong as varchar(500)
,@AuditDocsSaved as bit
,@AuditIncident as int output
as
BEGIN
SET NOCOUNT ON
Insert Into Audit_Findings
Values (@AuditRID,@EnteredBy,GETDATE(),@AuditItemNumber,@AuditFindingShort,@AuditFindingLong,@AuditDocsSaved)
declare @AuditFindingNumber as int
select @AuditFindingNumber = MAX(@@IDENTITY)
select @AuditIncident = @AuditFindingNumber
END
到目前为止,这是我的 VBA 代码。
--VBA Code
cnn.CursorLocation = adUseClient
cmd.ActiveConnection = cnn
cmd.CommandType = adCmdStoredProc
cmd.CommandText = "InternalReporting.dbo.Audit_InsertAuditFinding"
cmd.NamedParameters = True
Set prm = cmd.CreateParameter("@AuditRID", adInteger, adParamInput, 50, Audit_Topic.Value * 1)
cmd.Parameters.Append prm
Set prm = cmd.CreateParameter("@EnteredBy", adVarWChar, adParamInput, 10, Environ("UserName"))
cmd.Parameters.Append prm
Set prm = cmd.CreateParameter("@AuditItemNumber", adInteger, adParamInput, 10, Audit_ItemNumber.Value * 1)
cmd.Parameters.Append prm
Set prm = cmd.CreateParameter("@AuditFindingShort", adVarWChar, adParamInput, 50, Audit_ShortDescr.Value)
cmd.Parameters.Append prm
Set prm = cmd.CreateParameter("@AuditFindingLong", adVarWChar, adParamInput, 500, Audit_LongDescr.Value)
cmd.Parameters.Append prm
Set prm = cmd.CreateParameter("@AuditDocsSaved", adVarWChar, adParamInput, 500, Doc_Saved)
cmd.Parameters.Append prm
Set prm = cmd.CreateParameter("@AuditIncident", adVarWChar, adParamOutput, 10, Incident_Number.Value)
cmd.Parameters.Append prm
cmd.Execute
Incident_Number.Value = cmd.Parameters("@AuditIncident") * 1
SQL_String = "Delete from InternalReporting.dbo.Audit_Findings_Notifications where Audit_Incident = " & Incident_Number.Value * 1
rst.Open SQL_String, cnn, adOpenStatic
Set rst = Nothing
With AUD_02_Item_Mgmt.Notify_Overview
For I = 1 To .ListCount
SQL_String = "Insert Into InternalReporting.dbo.Audit_Findings_Notifications " & _
"Values (" & Incident_Number.Value & ",'" & .List(I - 1, 0) & _
"','" & .List(I - 1, 2) & "')"
rst.Open SQL_String, cnn, adOpenStatic
Set rst = Nothing
Next I
End With`