6

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!

4
  • What is your version? Commented Jun 21, 2017 at 12:00
  • Any version of SQL Server Commented Jun 21, 2017 at 12:01
  • DROP -> CREATE could lead to losing information about permissions. CREATE -> ALTER is safer. Commented Jun 23, 2017 at 8:46
  • could you please share any link to get the knowledge for this, it would be really appreciated. thanks @lad2025 Commented Jun 23, 2017 at 9:02

3 Answers 3

5

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

Sign up to request clarification or add additional context in comments.

Comments

3

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

Comments

1

With SQL Server 17 it's

Script DROP and CREATE

See: enter image description here

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.