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
Related
I have the following procedure for inserting into a user table:
-- ================================================
-- Template generated from Template Explorer using:
-- Create Procedure (New Menu).SQL
--
-- Use the Specify Values for Template Parameters
-- command (Ctrl-Shift-M) to fill in the parameter
-- values below.
--
-- This block of comments will not be included in
-- the definition of the procedure.
-- ================================================
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author: Andy Armstrong
-- Create date:
-- Description:
-- =============================================
CREATE PROCEDURE db_SignupAddLogin
-- Add the parameters for the stored procedure here
#LoginName VARCHAR(15),
#LoginPassword VARCHAR(15)
AS
BEGIN
DECLARE #GUID UNIQUEIDENTIFIER
SET #GUID = NEWID();
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
-- Insert statements for procedure here
INSERT INTO tblMemberLogin
(
UserID,
LoginName,
LoginPassword
)
VALUES
(
#GUID,
#LoginName,
#LoginPassword
)
RETURN #GUID
END
GO
However when I execute it I get the following error:
Msg 206, Level 16, State 2, Procedure db_SignupAddLogin, Line 34
Operand type clash: uniqueidentifier is incompatible with int
I cannot quite workout why as i am not referencing an int anywhere.
My Schema for tblMemberLogin looks like this:
UserID(PK,uniqueidentifier,notnull)
LoginName(nchar(15),not null)
LoginPassword(nchar(15),not null)
Please help!
RETURN can only be used with an int. You can simply use a SELECT query to retrieve the value of variable #GUID.
Reference: http://technet.microsoft.com/en-us/library/ms174998(v=sql.110).aspx
get rid of RETURN #GUID and you should be good to go.
In SQL Server, stored procedures may only return integer values. SQL Server RETURN
If you want to return data from a stored procedure other than an integer, you can use an output parameter: Returning Data from Stored Procedures
You declare the output parameter along with your input parameters:
CREATE PROCEDURE CREATE PROCEDURE db_SignupAddLogin
-- Add the parameters for the stored procedure here
#LoginName VARCHAR(15),
#LoginPassword VARCHAR(15),
#NewGuid UNIQUEIDENTIFIER OUTPUT
AS
BEGIN
SET #NewGuid = NEWID();
-- rest of procedure
END
And then use the output parameter:
DECLARE #NewLoginGuidFromSP UNIQUEIDENTIFIER
EXECUTE db_SignupAddLogin 'Username', 'password', #NewGuid = #NewLoginGuidFromSP OUTPUT;
I have three stored procedures A, B, C
and definition of A is like
StoredProcedure A
As
Begin
--Some Stuff
Exec DBO.B [Derived Conitions]
Exec DBO.C [Derived Conitions]
END
but whenever I tried to execute the stored procedure A, at parsing time it give waring;
The module 'A' depends on the missing object 'B'. The module will still be created;
however, it cannot run successfully until the object exists.
The module 'A' depends on the missing object 'C'. The module will still be created;
however, it cannot run successfully until the object exists.
At execution time it throws exception
Could not find stored procedure 'dbo.B'.
Could not find stored procedure 'dbo.C'.
I found so many answers for calling a stored procedure with in stored procedure, but none of them worked for me.
You certainly can execute multiple procedures from within a single SP. You can even us the results from 1 SP as parameters in another.
In your specific case I suspect that there is a permissions / security or collation error which is stopping you from access the B and C stored procs.
Here is an example of SP chaining at work.
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[DerivedProcedures]
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
-- Temporary table used to store results from SP1
DECLARE #Results_ForStoredProcedure1 TABLE
(
[SPID] INT,
[Status] NVARCHAR(50),
[Login] NVARCHAR(50),
[HostName] NVARCHAR(50),
[BlkBy] NVARCHAR(5),
[DBName] NVARCHAR(50),
[Commad] NVARCHAR(50),
[CPUTime] INT,
[DiskIO] INT,
[LastBatch] NVARCHAR(50),
[ProgramName] NVARCHAR(50),
[SPID2] INT,
[RequestId] INT
)
-- Execute SP1
INSERT INTO #Results_ForStoredProcedure1
EXEC sp_who2
-- Temporary table to store the results from SP2
DECLARE #Results_ForStoredProcedure2 TABLE
(
[DatabaseName] NVARCHAR(50),
[DatabaseSize] INT,
[Remarks] NVARCHAR(50)
)
-- Execute SP2
INSERT INTO #Results_ForStoredProcedure2
EXEC sp_databases
-- do something with both SP results
SELECT DISTINCT SP2.*
FROM #Results_ForStoredProcedure1 AS SP1
INNER JOIN #Results_ForStoredProcedure2 AS SP2 ON SP2.DatabaseName = SP1.DBName
WHERE SP1.DBName IS NOT NULL
END
GO
-- TEST
EXECUTE [dbo].[DerivedProcedures]
Perhaps, it sounds hilarious but I was getting the mentioned issue as I was using the wrong DB name (for example-Use 'XYZ'). Actually, in my case I was transferring a SP from one environment to another but after doing so I would not change the corresponding DB name .Due to which I was getting the error as the SPs which were involved were present in different DBs in the dissimilar environment.
In nutshell,please check the DB name which should be the very first line of your SP.
For example- Use 'XYZ'.
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.
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.
I want to call this procedure that sends one value that can be NULL or any int value.
SELECT DomainName, DomainCode FROM Tags.tblDomain WHERE SubDomainId =#SubDomainId
I simply want to use this single query rather than what i m doing right now in below given code.
I searched for this how could i do this then i got this Link.
According to this I have to set ANSI_NULLS OFF
I am not able to set this inside this procedure before executing my sql query and then reset it again after doing this.
ALTER PROCEDURE [Tags].[spOnlineTest_SubDomainSelect]
#SubDomainId INT
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
-- Insert statements for procedure here
IF #SubDomainId IS NULL
SELECT DomainName, DomainCode FROM Tags.tblDomain WHERE SubDomainId IS NULL
ELSE
SELECT DomainName, DomainCode FROM Tags.tblDomain WHERE SubDomainId =#SubDomainId
END
What will be the better practice to do deal with ANSI_NULLS or Using If Else
SET ANSI_NULLS is ony defined at stored proc create time and cannot be set at run time.
From CREATE PROC
Using SET Options
The Database Engine saves the settings
of both SET QUOTED_IDENTIFIER and SET
ANSI_NULLS when a Transact-SQL stored
procedure is created or modified.
These original settings are used when
the stored procedure is executed.
Therefore, any client session settings
for SET QUOTED_IDENTIFIER and SET
ANSI_NULLS are ignored when the stored
procedure is running. Other SET
options, such as SET ARITHABORT, SET
ANSI_WARNINGS, or SET ANSI_PADDINGS
are not saved when a stored procedure
is created or modified. If the logic
of the stored procedure depends on a
particular setting, include a SET
statement at the start of the
procedure to guarantee the appropriate
setting. When a SET statement is
executed from a stored procedure, the
setting remains in effect only until
the stored procedure has finished
running. The setting is then restored
to the value the stored procedure had
when it was called. This enables
individual clients to set the options
they want without affecting the logic
of the stored procedure.
The same applies to SET QUOTED_IDENTIFIER
In this case, use IF ELSE because SET ANSI_NULLS will be ON in the future.
Or Peter Lang's suggestion.
To be honest, expecting SubDomainId = #SubDomainId to work when #SubDomainId is NULL is not really correct usage of NULL...
Can't you use a single query?
SELECT DomainName, DomainCode
FROM Tags.tblDomain
WHERE ( #SubDomainId IS NULL AND SubDomainId IS NULL )
OR ( SubDomainId = #SubDomainId )
FYI, I'm pretty sure ...
ANSI_NULLS OFF
Applies to the procedure when you create/edit it, it's like a setting of the procedure.
So either the procedure has it ON or OFF. Your example was a query not a procedure so I'm a little confused.
But if you have SQL 2005/2008 for example if you "edit" procedure it opens up your procedure in a new tab you'll see the ANSI_NULLS OFF near the top.
You can edit it there and set it ON or OFF and update it to change ...