Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generate Script With If EXIST DROP But Do Not Include If Not Exists In CREATE In SQL Server

I want to generate the script using Tasks | Generate Scripts with IF Exist Drop Stored Procedure.

But I don't want to include IF NOT EXISTS - Create Stored Procedure while generating Script then what should I do?

Current

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SPNAME]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[SPNAME]
GO

IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SPNAME]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[SPNAME] AS' 
END
GO

Required

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SPNAME]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[SPNAME]
GO

CREATE PROCEDURE [dbo].[SPNAME] AS 

Can anyone please help me!

like image 895
pedram Avatar asked Jun 21 '17 11:06

pedram


People also ask

What happens on drop if exist and the table does not exist?

If the table does not exist and you do not include the IF EXISTS clause, the statement will return an error. Before dropping a table, you must first remove any stored procedures that reference the table.

What drop command do you use to drop a table and not incur an error if the table doesn't exist?

We use the SQL DROP Table command to drop a table from the database. It completely removes the table structure and associated indexes, statistics, permissions, triggers and constraints. You might have SQL Views and Stored procedures referencing to the SQL table.

How can you tell if a table is created or not in SQL?

Using the OBJECT_ID and the IF ELSE statement to check whether a table exists or not. Alternative 2 : Using the INFORMATION_SCHEMA. TABLES and SQL EXISTS Operator to check whether a table exists or not.


2 Answers

There is no direct option available to do this thing. Follow below step.

  1. Generate DROP scripts for all objects.

    • Include If NOT Exists = True
    • Script DROP and CREATE = Script DROP
  2. Generate CREATE scripts for all objects.

    • Include If NOT Exists = False
    • Script DROP and CREATE = Script CREATE
    • Append to File = True

2nd step will append contents of drops scripts which is generated in 1st step.

If you want to merge all files in one file then use bellow command

for %f in (*.sql) do type "%f" >> c:\Test\output.sql

Query Options

Query Options

Drop

Drop

Create

Create

like image 117
Rikin Patel Avatar answered Oct 14 '22 06:10

Rikin Patel


You can enable the "Check for object existence" option to true and generate the drop create script. It should work for 2017 or Azure SQL DB

enter image description here

like image 21
Rupesh Kumar Avatar answered Oct 14 '22 08:10

Rupesh Kumar