简体   繁体   English

使用 INTO 子句为每个员工代码创建表的存储过程

[英]Stored procedure to create tables for each employee code using INTO clause

I am trying to create tables which are specific to employee ID.我正在尝试创建特定于员工 ID 的表。

I can run simple select statement in a stored procedure.我可以在存储过程中运行简单的 select 语句。 But I want to create tables using INTO clause which I can then export into CSV files.但我想使用 INTO 子句创建表,然后我可以将其导出到 CSV 个文件中。 When I write INTO clause, I get an error "Incorrect syntax near 'zz_'".当我编写 INTO 子句时,出现错误“'zz_' 附近的语法不正确”。 If I hover mouse over 'zz_', I see error as "expecting '.', ID, or Quoted_ID".如果我 hover 将鼠标悬停在 'zz_' 上,我会看到错误为“期待 '.'、ID 或 Quoted_ID”。

I even tried to replace it using a variable called @table_employee (not included in below code).我什至尝试使用名为 @table_employee 的变量(未包含在下面的代码中)来替换它。 But even that code doesn't work.但即使是该代码也不起作用。 I do not want to use INSERT INTO way of writing query.我不想使用 INSERT INTO 方式编写查询。

Also is below code an efficient way of writing SQL program?下面的代码也是编写 SQL 程序的有效方法吗?

DECLARE @employeeID INT
DECLARE @deptartment VARCHAR(2)

SET @employeeID = (select MIN(ID) from employee)
SET @deptartment = 'HR'

WHILE @employeeID <= (SELECT MAX(ID) FROM employee)

BEGIN

    IF EXISTS 
    (
    select * from companydata
    where ID = @employeeID
    )

        select  a.employeeID, b.Name, 
            SUM(a.RATE * a.Quantity) 'Revenue'
        into 'zz_' + Region + '_' + Product + '_' + @employeeID
        from
            employee a join
            companydata b on a.employeeID = b.ID
        where a.employeeID = @employeeID and a.departmentname = @deptartment
        group by a.employeeID, b.Name, Region, Product
        order by a.employeeID, b.Name

    ELSE
        PRINT CAST(@employeeID as varchar) + ' Does not exist'

    SET @employeeID = @employeeID + 1

END

You don't really want a bunch of different tables for this.您真的不需要为此使用一堆不同的表。 A single summary table can efficiently hold the data for all employees, eg单个汇总表可以有效地保存所有员工的数据,例如

select  
    a.employeeID, 
    b.Name, 
    Region,
    Product 
    SUM(a.RATE * a.Quantity) 'Revenue'
into zz_HR_RevenueByEmployeeRegionProduct
from
    employee a join
    companydata b on a.employeeID = b.ID
where a.departmentname = 'HR'
group by a.employeeID, b.Name, Region, Product

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM