2

我正在尝试创建一个存储过程,该过程将能够限制使用部门 ID 返回的记录数。我试图通过加入临时表来限制记录。

当我运行下面的代码时,我得到了错误:

只有在使用列列表并且 IDENTITY_INSERT 为 ON 时,才能为表“#department”中的标识列指定显式值。

这是代码:

DECLARE @departmentID INT
SET @departmentID = 4

-- create temp department table --
select top 0 * into #department from PayrollDepartment

-- load temp department table
IF @departmentID < 1 OR @departmentID IS NULL
BEGIN
    INSERT INTO #department SELECT * FROM PayrollDepartment
END 
ELSE
BEGIN
    INSERT INTO #department SELECT * FROM PayrollDepartment WHERE PayrollDepartmentID =     @departmentID
END

我开始:

IF @departmentID < 1 OR @departmentID IS NULL
BEGIN
    SELECT * INTO #department FROM ApplicationEmployeeInfo..PayrollDepartment
END 
ELSE
BEGIN
    SELECT * INTO #department FROM ApplicationEmployeeInfo..PayrollDepartment WHERE PayrollDepartmentID = @departmentID
END

但我得到了错误:

数据库中已经有一个名为“#department”的对象

我不是 SQL 专家,所以也许有更好的方法来做到这一点?

4

1 回答 1

5

您的临时表具有标识列,因为SELECT .. INTO 复制了原始表的表结构,该表具有标识列。

我建议明确创建您的临时表,并列出您从部门中选择的列。在生产代码中使用 SELECT *几乎从来都不是一个好主意,所以我建议明确列出您的选择并插入到列中:

CREATE TABLE #Department
(   PayrollDepartmentID INT NOT NULL,
    <more columns>
);

IF @departmentID < 1 OR @departmentID IS NULL
    BEGIN
        INSERT #Department (PayrollDepartmentID, <more columns>)
        SELECT  PayrollDepartmentID, <more columns>
        FROM    PayrollDepartment;
    END
ELSE
    BEGIN
        INSERT #Department (PayrollDepartmentID, <more columns>)
        SELECT  PayrollDepartmentID, <more columns>
        FROM    PayrollDepartment
        WHERE   PayrollDepartmentID = @departmentID;
    END
    

它可能看起来需要更多的工作,而且肯定更冗长,但从长远来看,它是更好的实践和更健壮的方法。这也意味着您可以通过仅获取您实际需要的列来避免冗余PayrollDepartment

于 2013-11-25T17:38:49.170 回答