I am trying to create a stored procedure that will drop a table and then create a new table with the same name.
However, when I right clicked on the table and did Script Table as ... DROP and CREATE To ... New Query Editor Window
and then copied the script into a blank stored procedure, it wouldn't let me create the procedure because
There is already an object named 'MyTable' in the database
What should I do?
NOTE: the new table will not be the same structure as the old table. I make some transformations using other stored procedures to the table, so at the end, I want to drop it and create from scratch.
Here is the actual script:
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[spDropAndCreate]
AS
BEGIN
SET NOCOUNT ON;
IF OBJECT_ID ('dbo.MyTable','U') IS NOT NULL
DROP TABLE [dbo].[MyTable]
CREATE TABLE [dbo].[MyTable]
(
[ID] [int] IDENTITY(1,1) NOT NULL,
[Col1] [nvarchar](50) NULL,
[Col2] [nvarchar](50) NULL,
[Col3] [nvarchar](50) NULL,
[Col4] [nvarchar](50) NULL,
[Col5] [nvarchar](50) NULL,
[Col6] [nvarchar](50) NULL,
[Col7] [nvarchar](50) NULL,
[Col8] [nvarchar](50) NULL,
[Col9] [nvarchar](50) NULL,
[Col10] [nvarchar](50) NULL
)
GO
END
Here is the error message:
Msg 102, Level 15, State 1, Procedure spDropAndCreate, Line 17 [Batch Start Line 9]
Incorrect syntax near 'MyTable'Msg 2714, Level 16, State 6, Line 35
There is already an object named 'MyTable' in the databaseMsg 102, Level 15, State 1, Line 156
Incorrect syntax near 'END'