简体   繁体   English

无法执行 SQL 服务器存储过程

[英]Unable to execute SQL Server stored procedure

I get the following error when trying to execute a stored procedure:尝试执行存储过程时出现以下错误:

Msg 2714, Level 16, State 6, Procedure Hire_Termination, Line 18 [Batch Start Line 2]消息 2714,级别 16,State 6,过程 Hire_Termination,第 18 行 [批处理开始第 2 行]
There is already an object named 'Employees' in the database数据库中已经有一个名为“Employees”的 object

I created the table in another instance, I have to use a JSON file and import it into SQL Server:我在另一个实例中创建了表,我必须使用 JSON 文件并将其导入 SQL 服务器:

USE [Kronos]
GO

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

ALTER PROCEDURE [dbo].[Hire_Termination]
AS
    DECLARE @JSON nvarchar(max)
    SET @JSON = N'{C:\Automation\Kronos.JSON}'
BEGIN
    SELECT @JSON = BulkColumn
    FROM OPENROWSET (BULK 'C:\Automation\Kronos.JSON', Single_Clob) import

    SET NOCOUNT ON;

    SELECT * 
    INTO [Kronos].[dbo].[Employees]
    FROM OPENJSON (@JSON)
END

SELECT INTO creates a new table. SELECT INTO创建一个新表。 So instead of using所以而不是使用

SELECT * 
INTO [Kronos].[dbo].[Employees]
FROM OPENJSON (@JSON);

use a regular INSERT statement eg使用常规的INSERT语句,例如

INSERT INTO [Kronos].[dbo].[Employees]
SELECT * 
FROM OPENJSON (@JSON);

Note: Its best practice to fully list the columns you are inserted and selecting eg注意:最好的做法是完整列出您插入的列选择例如

INSERT INTO [Kronos].[dbo].[Employees] (Col1, Col2, Col3, ...)
SELECT Col1, Col2, Col3, ...
FROM OPENJSON (@JSON);

SELECT INTO creates a new table. SELECT INTO 创建一个新表。 So the second time you run the SP, it will complain If you want to insert into an existing table then use INSERT INTO Kronos.dbo.Employees SELECT... If you really want to just replace the contents of the table then you could run DROP TABLE IF EXISTS Kronos.dbo.Employees first, then SELECT INTO statement.因此,第二次运行 SP 时,它会报错如果您想插入现有表然后使用 INSERT INTO Kronos.dbo.Employees SELECT ... 如果您真的只想替换表的内容,那么您可以运行DROP TABLE IF EXISTS 首先是 Kronos.dbo.Employees,然后是 SELECT INTO 语句。

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

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