简体   繁体   中英

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]
There is already an object named 'Employees' in the database

I created the table in another instance, I have to use a JSON file and import it into SQL Server:

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. So instead of using

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

use a regular INSERT statement eg

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. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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