Mix Create Stored Procedure and Insert Statements in Sql Server - sql

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

Related

Procedure created with CREATE PROCEDURE Defaults with ALTER PROCEDURE

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

Cannot set IMPLICIT_TRANSACTIONS to OFF for stored procedure?

I have a Stored Procedure in which I'm NOT using any explicit Transaction related code (i.e. begin/rollback/commit transaction), and yet ##Trancount is set to 2 (I'm monitoring this by writing this value into a Table's row entry during the Stored Procedure). This obviously means thats IMPLICIT_TRANSACTIONS is set to ON somewhere.
I'm adding the following lines to the start of my Stored Procedure ....
SET IMPLICIT_TRANSACTIONS OFF
GO
.... So that it becomes this:
USE [RentTrackingSystem]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET IMPLICIT_TRANSACTIONS OFF
GO
ALTER PROCEDURE [RTS].[GenerateAnnualPenalty]
-- Add the parameters for the stored procedure here
#dueDate Date = NULL ,
#fiscalYear numeric(4),
#createdBy Varchar(50),
#referenceForm Varchar(50),
#referenceFormNo Varchar(50),
#PENALTY_NO int ,
#PenaltyCutOffDate date = NULL
AS
-- Rest of the body here ..
However when I execute the query (to Alter the Stored Procedure), close that window and then again open the same Stored Procedure's code, that addition goes away, and the Stored Procedure again becomes:
USE [RentTrackingSystem]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [RTS].[GenerateAnnualPenalty]
-- Add the parameters for the stored procedure here
#dueDate Date = NULL ,
#fiscalYear numeric(4),
#createdBy Varchar(50),
#referenceForm Varchar(50),
#referenceFormNo Varchar(50),
#PENALTY_NO int ,
#PenaltyCutOffDate date = NULL
AS
-- Rest of the body here ..
So what's going on here ?
You can't get SET IMPLICIT_TRANSACTIONS OFF before the body of the stored procedure because this is not a value that is captured when a stored procedure is created. When you set the implicit_transactions to off all you're doing is setting the the value for your connection so when you run your alter statement you'll be running it under the context of having implicit_transactions turned off, but there is no relation to that setting and what is captured for the stored procedure definition.
To put it another way there are many settings that are affecting your queries at any given time, but SQL Server only captures ANSI_NULLS and QUOTED_IDENTIFIER settings when creating a stored procedure.
Per MSDN:
When a stored procedure is created, the SET QUOTED_IDENTIFIER and SET ANSI_NULLS settings are captured and used for subsequent invocations of that stored procedure.
If you want the content of the sproc to be affected by the SET IMPLICIT_TRANSACTIONS OFF setting simply set it as the first thing after the Create Proc Name (variables Datatypes) As... sproc declaration.
Note that this is not going to clear out existing transactions. If you have transactions outside of the stored procedure they will still exist, this setting is simply going to prevent any new implied transactions from being created.

SET XACT_ABORT ON not Worked in Create Procedure

I use SQL Server 2008 SP3 (10.0.5500) And I have some Problems with Rollback Transactions, at first I need to know something. This is My create Procedure script:
USE [MYDB]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET XACT_ABORT ON
GO
If Exists(Select * From Sys.Objects Where [object_id]=Object_Id(N'[Members].[MyProc]') And ObjectProperty([object_id], N'IsProcedure') = 1)
Begin
Drop Procedure [Members].[MyProc]
Print 'Procedure [Members].[MyProc] Dropped!'
End
GO
CREATE PROCEDURE [Members].[MyProc](
....
)
AS
BEGIN
BEGIN TRANSACTION [MyProcCHK]
....
COMMIT TRANSACTION [MyProcCHK]
END
GO
And After run this script, I check Procedure from: MyDB ->Programmability->StoredProcedures And Click to Modify [Members].[MyProc] Then this is the script shown:
USE [MYDB]
GO
/****** Object: StoredProcedure ... ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [Members].[MyProc](
....
)
AS
BEGIN
BEGIN TRANSACTION [MyProcCHK]
....
COMMIT TRANSACTION [MyProcCHK]
END
GO
So Where is SET XACT_ABORT ON? And why that not displayed here? As I have some problems with rollback transactions in stored procedures I think the SET XACT_ABORT ON never saved. Am I right? and if yes, what is the solution? I can't use SET XACT_ABORT ON in stored procedures? or where is my fault?
You need to mention set xact_abort on inside the Create procedure statement
CREATE PROCEDURE [Members].[MyProc](
........
)
AS
SET XACT_ABORT ON
BEGIN
BEGIN TRANSACTION [MyProcCHK]
....
COMMIT TRANSACTION [MyProcCHK]
END
GO

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.

Failed to call a stored procedure within another stored procedure

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
Create PROCEDURE [dbo].[SD_Sproc_Insurance_Insert]
-- Add the parameters for the stored procedure here
(
#HCSInsuranceID bigint,
#HCSInsuranceCode varchar(10),
#HCSInsuranceName varchar(100),
#IsPPS bit,
#IsActive bit
)
AS
BEGIN TRAN InsuranceInsert
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
INSERT INTO SD_Sproc_ToGRS_Insurance(HCSInsuranceID ,HCSInsuranceCode, HCSInsuranceName, IsPPS ,IsActive)
VALUES (#HCSInsuranceID ,#HCSInsuranceCode, #HCSInsuranceName, #IsPPS, #IsActive);
COMMIT TRAN InsuranceInsert
The SD_Sproc_ToGRS_Insurance is the stored that I'll call.. I'm having a problem to call this one. Anyone suggest? That I'm doing the right path to call a stored procedure?
The above is SQL Server syntax. Use the exec command like so to call a stored procedure.
exec storedProcName #param1Name, #param2Name