Procedure created with CREATE PROCEDURE Defaults with ALTER PROCEDURE - sql

I have a SQL Script that creates a procedure that looks like this:
IF OBJECT_ID('dbo.InitMyTable') IS NOT NULL
DROP PROCEDURE [dbo].[InitMyTable]
GO
CREATE PROCEDURE [dbo].[InitMyTable] AS
BEGIN
CREATE TABLE MyTable (
ID int,
Name varchar(16),
Data text
);
END
And it creates a procedure that looks like this:
GO
/****** Object: StoredProcedure [dbo].[InitMyTable] Script Date: 5/19/2017 12:30:45 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[InitMyTable] AS
BEGIN
CREATE TABLE myTable (
ID int,
Name varchar(16),
Data text
);
END
My issue is that the created procedure does not create the table, but when I remove the line
ALTER PROCEDURE [dbo].[InitMyTable] AS
It obviously works fine.
How can I create a script that produces a procedure without that line?

It looks like you scripted out the stored procedure somehow-- possibly in SQL Server Management Studio (SSMS) by right-clicking the proc in the Object Explorer window and clicking "Modify". When you do this, SSMS generates a script for you that will alter the existing stored procedure.
The DDL statements below create the procedure, but they are not part of the procedure:
IF OBJECT_ID('dbo.InitMyTable') IS NOT NULL
DROP PROCEDURE [dbo].[InitMyTable]
GO
CREATE PROCEDURE [dbo].[InitMyTable] AS
The same thing applies to the code generated by SSMS. SSMS has generated code that can alter an existing stored procedure, but the DDL below is not actually part of the proc itself:
/****** Object: StoredProcedure [dbo].[InitMyTable] Script Date: 5/19/2017 12:30:45 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[InitMyTable] AS
The stored procedure code itself is still there:
CREATE TABLE MyTable (
ID int,
Name varchar(16),
Data text
);
Note that if this stored procedure is run twice, it will fail, because the table MyTable will already exist. To avoid this error, the procedure could first check to see if the table exists:
if not exists (select 1 from sys.tables where name = 'MyTable')
begin
create table MyTable...
end

Related

Check if stored procedure exists accordingly create or alter

I want to check if a stored procedure already defined in db. If defined I have to execute alter script else create.
IF EXISTS (SELECT * FROM sysobjects WHERE type = 'P' AND name = 'EmployeeInternalReferenceNumber_Copy')
BEGIN
DROP Procedure [dbo].[EmployeeInternalReferenceNumber_Copy]
END
Go
CREATE PROCEDURE [dbo].[EmployeeInternal]
Above script is not working as I do not want to drop proc just alter or create. I am using SP2
In SQL Server version 2016+, you can simply use:
CREATE OR ALTER PROCEDURE [dbo].[EmployeeInternal]
AS
You can use drop procedure if exists instead of if exists
DROP PROCEDURE IF EXISTS EmployeeInternalReferenceNumber_Copy;
CREATE PROCEDURE [dbo].[EmployeeInternal]
Or if you want to alter procedure EmployeeInternal then use alter instead of create
ALTER PROCEDURE [dbo].[EmployeeInternal]

Update stored procedure using C#?

I have 10 database servers and most procedures are the same.
So I plan to make procedure distribute program.
For convenient application, I want to use "the procedure modify code made by tool" itself.
For example, when I click modify button of the procedure on SSMS the code is like below.
USE [DB]
GO
/****** Object: StoredProcedure [dbo].[HongTestProcedure] Script Date: 2020-08-28 오전 11:09:02 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author: hong
-- Create date: 2020-03-07
-- =============================================
ALTER PROCEDURE [dbo].[HongTestProcedure]
-- Add the parameters for the stored procedure here
#ID varchar(10)
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
SELECT *
FROM table
END
And then, if I want to modify the parameter of the procedure.
Maybe the code is like below:
USE [DB]
GO
/****** Object: StoredProcedure [dbo].[HongTestProcedure] Script Date: 2020-08-28 오전 11:09:02 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author: hong
-- Create date: 2020-03-07
-- =============================================
ALTER PROCEDURE [dbo].[HongTestProcedure]
-- Add the parameters for the stored procedure here
#ID varchar(10)
#ID2 varchar(10) -- it is added.
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
SELECT *
FROM table
END
I consider that program has a textbox and button.
and I want to insert all above code.
maybe it looks like it:
So, I try the code like below:
public bool UpdateProcedure(string dbip, string query)
{
DataSet ds = new DataSet();
SqlConnection sqlConn = new SqlConnection("server = " + dbip + dbInfo);
sqlConn.Open();
SqlCommand sqlComm = new SqlCommand(query, sqlConn);
sqlComm.ExecuteNonQuery();
return true;
}
If it run successfully, I will run query on 10 database servers.
But it return error message. even it can be run in SSMS.
incorrect syntax near 'GO'
CREATE/ALTER PROCEDURE must be the first statement in a query batch
Can I solve it?
Yes. Since you can construct it as an Dynamic SQL in C# and Open an SQL Connection and pass the Dynamic SQL to EXEC sp_executesql #DynamicSQL. This will create the required SP in the required Database.

How to add header comments when altering stored procedures in SQL Server

I have a stored procedure where there are no header comments. I want to add them, but whenever I try, it is not included.
In SQL Server Management Studio I :
1.Right-click my stored procedure and click modify
USE [ABigDB]
GO
/****** Object: StoredProcedure [dbo].[spDoWork] Script Date: 21/08/2015 14:11:45 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[spDoWork]
#Id uniqueidentifier,
#Session nvarchar(50),
#XMLData xml
WITH EXECUTE AS OWNER
AS
BEGIN
--etc etc...
END
2.I paste comments above the stored procedure and run the script :
-- Stored Procedure
-- Author: Dave
-- Create date: 21/08/2015
-- Description: Does Stuff
-- Change history
-- 07/08/2015 - Overlord - Done stuff
-- 06/08/2015 - Kerrigan - Done more stuff
USE [ABigDB]
GO
/****** Object: StoredProcedure [dbo].[spDoWork] Script Date: 21/08/2015 14:11:45 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[spDoWork]
#Id uniqueidentifier,
#Session nvarchar(50),
#XMLData xml
WITH EXECUTE AS OWNER
AS
BEGIN
--etc etc...
END
3.When I modify the same stored procedure it appears as :
USE [ABigDB]
GO
/****** Object: StoredProcedure [dbo].[spDoWork] Script Date: 21/08/2015 14:11:45 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[spDoWork]
#Id uniqueidentifier,
#Session nvarchar(50),
#XMLData xml
WITH EXECUTE AS OWNER
AS
BEGIN
--etc etc...
END
So how do I get the comments to appear there?
I solved it by doing the following:
USE [ABigDB]
GO
/****** Object: StoredProcedure [dbo].[spDoWork] Script Date: 21/08/2015 14:11:45 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- Stored Procedure
-- Author: Dave
-- Create date: 21/08/2015
-- Description: Does Stuff
-- Change history
-- 07/08/2015 - Overlord - Done stuff
-- 06/08/2015 - Kerrigan - Done more stuff
ALTER PROCEDURE [dbo].[spDoWork]
#Id uniqueidentifier,
#Session nvarchar(50),
#XMLData xml
WITH EXECUTE AS OWNER
AS
BEGIN
--etc etc...
END
Consider using the meta data in addition to your procedures, tables, columns, etc. for documentation purposes.
See the following that helps when reviewing your db objects.
Is it possible to add a description/comment to a table in Microsoft SQL 2000+

Invalid Object Name - Stored Procedure

I am creating a stored procedure in SQL Server via SSMS.
I have written the stored procedure below, however when I click execute it am given the error:
Msg 208, Level 16, State 6, Procedure NewQuestion, Line 11
Invalid object name 'hgomez.NewQuestion'.
the table is ownership is correct. (hgomez.Questions)
USE [devworks_oscar]
GO
/****** Object: StoredProcedure [hgomez].[NewQuestion] Script Date: 10/23/2011 23:55:08 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [hgomez].[NewQuestion]
(
#QUESTIONNAME nvarchar(50),
#QUESTION_ID int OUTPUT
)
AS
/* SET NOCOUNT ON */
INSERT INTO [Questions] (QuestionText) VALUES (#QUESTIONNAME)
SET #QUESTION_ID = SCOPE_IDENTITY();
RETURN
Thanks in advance
I was a fan of always prepending my CREATE statements with an explicit check for existence and dropping if it was found.
IF EXISTS (SELECT * FROM INFORMATION_SCHEMA.ROUTINES WHERE ROUTINE_NAME = 'NewQuestion' AND ROUTINE_SCHEMA = 'hgomez')
BEGIN
DROP PROCEDURE hgomez.NewQuestion
END
GO
-- this is always a CREATE
CREATE PROCEDURE [hgomez].[NewQuestion]
(
#QUESTIONNAME nvarchar(50),
#QUESTION_ID int OUTPUT
)
AS
/* SET NOCOUNT ON */
INSERT INTO [Questions] (QuestionText) VALUES (#QUESTIONNAME)
SET #QUESTION_ID = SCOPE_IDENTITY();
RETURN
That can be a bit of hassle with regard to permissions so others use an approach wherein they create a stub method only to immediately ALTER it.
IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.ROUTINES WHERE ROUTINE_NAME = 'NewQuestion' AND ROUTINE_SCHEMA = 'hgomez')
BEGIN
EXEC ('CREATE PROCEDURE hgomez.NewQuestion AS SELECT ''stub version, to be replaced''')
END
GO
-- This is always ALTER
ALTER PROCEDURE [hgomez].[NewQuestion]
(
#QUESTIONNAME nvarchar(50),
#QUESTION_ID int OUTPUT
)
AS
/* SET NOCOUNT ON */
INSERT INTO [Questions] (QuestionText) VALUES (#QUESTIONNAME)
SET #QUESTION_ID = SCOPE_IDENTITY();
RETURN
This script tries to modify a procedure that already exists; it doesn't create the procedure.
To create the procedure use CREATE PROCEDURE
CREATE PROCEDURE [hgomez].[NewQuestion]
Once the procedure exists, you can modify its definition by using ALTER PROCEDURE
ALTER PROCEDURE [hgomez].[NewQuestion]
This solution https://stackoverflow.com/a/26775310/2211788 explained
If you drop and re-create a stored procedure it gets a new objectid - the list of stored procedures in SSMS is linked to the id it knows at the time the list was built. If you re-create it but don't refresh the stored procedures folder then any attempts to edit it will indicate the procedure is not found as the id has changed.
This happened to me once when I had two instances of SSMS open and I was working on the one I opened first. Closed them both down, reopened and it worked fine.

Mix Create Stored Procedure and Insert Statements in Sql Server

I created a number of scripts to be run separately but was asked to combine them all so the DBA only has to do it once. The problem is that I cannot seem to combine them to run together. Only the first item in the query gets run. How do I format these to run together in one big script?
USE [DEV]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
Create PROCEDURE [dbo].[Projects]
#ProjectID int,
#ClientID int
AS
BEGIN
.....Cool procedure here
END
GRANT EXECUTE ON [dbo].[Projects] TO Admin, Employee
INSERT INTO random_table(stuff)
VALUES (stuff)
Add a GO between statements
USE [DEV]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
Create PROCEDURE [dbo].[Projects]
#ProjectID int,
#ClientID int
AS
BEGIN
.....Cool procedure here
END
GO -- Add GO here
GRANT EXECUTE ON [dbo].[Projects] TO Admin, Employee
GO -- Add GO here
INSERT INTO random_table(stuff)
VALUES (stuff)
USE [DEV]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
Create PROCEDURE [dbo].[Projects]
#ProjectID int,
#ClientID int
AS
BEGIN
.....Cool procedure here
END
GRANT EXECUTE ON [dbo].[Projects] TO Admin, Employee
GO -- added this "go" statement
INSERT INTO random_table(stuff)
VALUES (stuff)
Insert GO after each statement.
USE [DEV]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
Create PROCEDURE [dbo].[Projects]
#ProjectID int,
#ClientID int
AS
BEGIN
.....Cool procedure here
END
GO //add Go after every statement
GRANT EXECUTE ON [dbo].[Projects] TO Admin, Employee
GO
INSERT INTO random_table(stuff)
VALUES (stuff)
Although, I would recommend you to generate script of Database schema (including Stored procedures, functions, table creation, insertion, updation and deletion) from your SQL server database and save it with .SQL file and you don't have to place these GOs manually. Take a look at this fine example