将多个表插入一个表中

时间:2014-05-14 22:07:36

标签: sql sql-server tsql sql-server-2008-r2

我是一名新的程序员分析师。我正在学习SQL,我正在尝试将多个表中的数据(所有表具有相同的字段)插入到一个大型历史表中。是否有捷径可寻?到目前为止我有这个,但我知道这是错的:

Create Procedure InsertTables  
@ExistingTableName nvarchar(50) 
AS

   insert into EMF_Archive    
select      
em_Employee_ID,
em_Payroll_Unit,
em_Name,
em_Payroll_Unit_2,
em_Last_Name,
em_First_Name,
em_Middle_Initial,
em_Social_Security_No,
em_Payroll_Group,
em_Employee_Status,
em_Hire_Date,
em_Rehire_Date,
em_Adjusted_Hire_Date,
em_Birth_Date,
em_Termination_Date,
em_Organization,
em_Title,
em_Work_Comp,
em_Annual_Pay,
em_Salary_Rate,
em_Tax_Group,
em_Seniority_Date,
em_service_Years,
em_Service_Months,
em_Grade,
em_Variable_3,
em_Variable_4,
em_Standard_Hours,
em_Variable_10,
em_Variable_11,
em_Shift
from @ExistingTableName  

GO

EXEC InsertTables 'emf_payPeriod1'

我想这样执行几次:

EXEC InsertTables 'emf_payPeriod1'
EXEC InsertTables 'emf_payPeriod2'
EXEC InsertTables 'emf_payPeriod3'
  etc

等.....

1 个答案:

答案 0 :(得分:3)

你不能像你想要的那样传递表名,你需要使用动态sql,如下所示......

Create Procedure InsertTables  
@ExistingTableName nvarchar(128) 
AS
BEGIN
  SET NOCOUNT ON;

  DECLARE @Sql NVARCHAR(MAX);

SET @Sql = N' INSERT INTO EMF_Archive    
            select      
            em_Employee_ID,
            em_Payroll_Unit,
            em_Name,
            em_Payroll_Unit_2,
            em_Last_Name,
            em_First_Name,
            em_Middle_Initial,
            em_Social_Security_No,
            em_Payroll_Group,
            em_Employee_Status,
            em_Hire_Date,
            em_Rehire_Date,
            em_Adjusted_Hire_Date,
            em_Birth_Date,
            em_Termination_Date,
            em_Organization,
            em_Title,
            em_Work_Comp,
            em_Annual_Pay,
            em_Salary_Rate,
            em_Tax_Group,
            em_Seniority_Date,
            em_service_Years,
            em_Service_Months,
            em_Grade,
            em_Variable_3,
            em_Variable_4,
            em_Standard_Hours,
            em_Variable_10,
            em_Variable_11,
            em_Shift
            from ' + QUOTENAME(@ExistingTableName)

   EXECUTE sp_executesql  @Sql
END

GO

执行程序

为了对所有表执行此过程,您可以执行以下查询

--Make sure the following query is pulling all the required tables
SELECT name INTO #Tables
from sys.tables
WHERE name like 'emf_payPeriod%'

-- Now use that temp table to pass table names to your procedure
DECLARE @TableName NVARCHAR(128);

WHILE EXISTS (SELECT 1 FROM #Tables)
BEGIN
  SELECT TOP 1 @TableName = name FROM #Tables

  EXECUTE InsertTables @TableName

  DELETE FROM #Tables WHERE name = @TableName
END