在存储过程中使用插入语句从一个表中复制一些信息,并从VBA插入新信息

时间:2018-06-19 16:45:24

标签: sql sql-server vba stored-procedures

我正在创建一个存储过程,该过程将复制表1中的某些列并将其值插入表2的新条目中。同时,需要使用以下命令更新表2的新条目中的4列日期,用户名和VBA用户窗体上的按钮中的两个变量。

我知道如何单独执行这些操作,但是我不确定如何使它们协同工作。我可以做出两个声明,但是我都需要它们都转到表2上的同一条目,而不是两个单独的条目。

以下是我想合并为一个存储过程以通过VBA按钮单击创建一个新条目的两条语句。

SET IDENTITY_INSERT [PIA].[dbo].[AttendanceHistory] ON 
INSERT INTO [PIA].[dbo].[AttendanceHistory] (FirstName, LastName, AgentName, Location,
              EmployeeGroup, ContractAgency, Manager, Supervisor, Team, Title, Position, 
              Staffcimid, FTPT, Bilingual, Five9Email, Email, Weekdayschedule, 
              Weekendschedule, CreatedBy, CreatedDate, Exception, Exceptionreason)
SELECT FirstName, LastName, AgentName, Location, EmployeeGroup, ContractAgency, Manager, 
       Supervisor,Team, Title, Position, Staffcimid, FTPT, Bilingual, Five9Email, Email, 
       Weekdayschedule, Weekendschedule
FROM dbo.Attendance WHERE dbo.Attendance.Agentname = @Agent

Set [CreatedDate] = GETDATE and 
    [CreatedBy] = @userid and 
    [Exception] = @except and 
    [ExceptionReason] = @Exceptreason 

2 个答案:

答案 0 :(得分:1)

看看这是否有帮助:)

INSERT INTO [PIA].[dbo].[AttendanceHistory] (FirstName,LastName,AgentName,Location,EmployeeGroup,ContractAgency,Manager,Supervisor,Team,Title,Position,Staffcimid,FTPT,Bilingual,Five9Email,Email,Weekdayschedule,Weekendschedule,CreatedBy,CreatedDate,Exception,Exceptionreason)
SELECT FirstName,LastName,AgentName,Location,EmployeeGroup,ContractAgency,Manager,Supervisor,Team,Title,Position,Staffcimid,FTPT,Bilingual,Five9Email,Email,Weekdayschedule,Weekendschedule, GETDATE() , @userid, @except, @Exceptreason
FROM dbo.Attendance WHERE dbo.Attendance.Agentname = @Agent

答案 1 :(得分:1)

最好的方法是在select子句中传递变量,如下所示:

INSERT INTO [PIA].[dbo].[AttendanceHistory] (FirstName, LastName, AgentName, Location,
              EmployeeGroup, ContractAgency, Manager, Supervisor, Team, Title, Position, 
              Staffcimid, FTPT, Bilingual, Five9Email, Email, Weekdayschedule, 
              Weekendschedule, CreatedBy, CreatedDate, Exception, Exceptionreason)
SELECT FirstName, LastName, AgentName, Location, EmployeeGroup, ContractAgency, Manager, 
       Supervisor,Team, Title, Position, Staffcimid, FTPT, Bilingual, Five9Email, Email, 
       Weekdayschedule, Weekendschedule, GETDATE() , @userid, @except, @Exceptreason
FROM dbo.Attendance WHERE dbo.Attendance.Agentname = @Agent

GETDATE() , @userid, @except, @Exceptreason与表Attendence的列列表一起添加,因此成为常量字段。