How to incorporate a series of stored procedures inside a larger stored procedure - sql

I`m hitting a block here in SQL server , I have a bunch of small insert stored procedures, and I want to call upon them when creating one unified procedure.
I have these tables:
CREATE TABLE [Member]
(
[MemberID] Int IDENTITY(1,1),
[ProgID] int,
[MemberCardID] int,
[CECID] int,
[MFirstName] VarChar (60),
[MLastName] VarChar (60),
[MDateJoined] DateTime,
PRIMARY KEY ([MemberID]),
FOREIGN KEY ([ProgID]) REFERENCES [Program]
);
CREATE TABLE [MemberCard]
(
[MemberCardID] int IDENTITY(1,1),
[MemberID] int,
[MemberDetailsID] int,
[MActiveORInactive] varchar (1),
[Photo] image,
[LastLogin] DateTime,
[LoginFreq] Varchar,
[PaymentUTD] varchar,
[IssueDate] Date,
[NoOfCards] int,
PRIMARY KEY ([MemberCardID]),
FOREIGN KEY ([MemberID]) REFERENCES [Member] ,
);
CREATE TABLE [MemberDetails]
(
[MemberDetailsID] int IDENTITY(1,1),
[MemberCardID] int,
[PaymentID] int,
[CMAddress] Varchar (100),
[CMCity] VarChar (50),
[CMEmail] Varchar (100),
[CMPhone] int ,
PRIMARY KEY ([MemberDetailsID]),
FOREIGN KEY ([MemberCardID]) REFERENCES [MemberCard]
)
CREATE TABLE [EmergencyContact]
(
[CECID] Int IDENTITY(1,1),
[MemberHistoryID] Int,
[CECFirstName] VarChar(60),
[CECLastName] Varchar(60),
[CECPhone] Int,
[CECAddress] Varchar ( 100 ),
[CECDateUpdated] DateTime,
PRIMARY KEY ([CECID]) ,
FOREIGN KEY ([MemberHistoryID]) RERERENCES [MemberHistory]
)
And I have these smaller procedures:
CREATE PROCEDURE InsertMember
#MFirstName varchar(60),
#MLastName varchar(60)
AS
BEGIN TRAN
DECLARE #MemberID int
SET #MemberID = SCOPE_IDENTITY()
INSERT INTO Member(MFirstName, MLastName, MDateJoined)
VALUES (#MFirstName, #MLastName, GETDATE())
IF ##ERROR <> 0 OR ##ROWCOUNT > 1
BEGIN
ROLLBACK TRAN
PRINT 'ERROR Inserting Member'
SELECT ERROR_MESSAGE() AS ErrorMessage
RETURN -1
END
else
begin
Commit Tran
print 'Member Inserted Successfully'
return 0
end
go
CREATE procedure InsertMemberDetails
#CMAddress varchar(100),
#CMCity varchar (50),
#CMEmail varchar (100),
#CMPhone int
AS
begin tran
declare #MemberDetailsID int
set #MemberDetailsId = SCOPE_IDENTITY()
insert into MemberDetails(CMAddress,CMCity,CMEmail,CMPhone)
values (#CMAddress,#CMCity,#CMEmail,#CMPhone)
if ##ERROR <> 0 or ##ROWCOUNT >1
begin
ROLLBACK TRAN
print 'ERROR Inserting MemberDetails!!!'
select ERROR_MESSAGE() AS ErrorMessage
return -1
end
else
begin
Commit Tran
print 'MemberDetails Inserted Successfully'
return 0
end
go
CREATE procedure InsertEmergencyContact
#CECFirstName varchar(60),
#CECLastName varchar (60),
#CECPhone int ,
#CECAddress varchar (100)
AS
begin tran
declare #CECID int
set #CECID = SCOPE_IDENTITY()
insert into EmergencyContact(CECFirstName,CECLastName,CECPhone,CECAddress,CECDateUpdated)
values (#CECFirstName,#CECLastName,#CECPhone,#CECAddress,Getdate())
if ##ERROR <> 0 or ##ROWCOUNT >1
begin
ROLLBACK TRAN
print 'ERROR Inserting Emergency Contact Details!!!'
select ERROR_MESSAGE() AS ErrorMessage
return -1
end
else
begin
Commit Tran
print 'Emergency Contact Details Inserted Successfully'
return 0
end
go
And I want to create one single procedure where I execute the smaller ones but how do I do that?
Obviously the one below doesn't work:
CREATE procedure Proc_InsertNewMember
#MFirstName varchar(60),
#MLastName varchar(60),
#CMAddress varchar(100),
#CMCity varchar(50),
#CMPhone int ,
#CMEmail varchar(100),
#CECFirstName varchar(60),
#CECLastName varchar (60),
#CECPhone int,
#CECAddress Varchar (100),
#CECDateUpdated date
as
begin
insert into Member (MFirstName,MLastName,MDateJoined)
exec InsertMember ( #MFirstName , #MLastName , GetDate())
declare #MemberID int
select #MemberID = SCOPE_IDENTITY()
exec InsertMemberDetails [#CMAddress,#CMCity,#CMPhone,#CMEmail]
exec InsertEmergencyContact [#CECFirstName,#CECLastName,#CECPhone,#CECAddress ,#CECDateUpdated]
end
if ##error <> 0 or ##rowcount <> 1
begin
print 'ERROR'
end
else
return -1
end
But how can I call upon them procedures, so that I will just end up with one line that goes:
exec Proc_InsertNewMember 'Michael','Goodwin','Za Cool Street','Limerick','7843273',
'dhajsdhjas#dsjai.com','Rachel','Green','2121321','The other cool street','02/02/2020'

Related

Error converting data type varchar to int.?

My table is below
CREATE TABLE Customers
(
CustomerID int identity(1,1) not null primary key,
Name varchar(50) not null,
PhoneNumber varchar(20) not null
constraint chk_PhoneNumber check(PhoneNumber not like '%[^0-9]%'),
DoorNo varchar(50) not null,
StreetName varchar(50) not null,
City varchar(50) not null,
Statee varchar(50) not null,
Zipcode int not null
)
My stored procedure:
ALTER PROCEDURE stp_customers_insert
(#customerid int,
#name varchar(50),
#phone varchar(50),
#doorno varchar(50),
#streetname varchar(50),
#city varchar(50),
#state varchar(50),
#zip int)
AS
BEGIN
IF EXISTS (SELECT CustomerID FROM Customers WHERE CustomerID = #customerid)
BEGIN
RAISERROR ('employee id already exists', 1, 1)
END
ELSE
BEGIN
INSERT INTO Customers (Name, PhoneNumber, DoorNo, StreetName, City, Statee, Zipcode)
VALUES (#name, #phone, #doorno, #streetname, #city, #state, #zip)
END
END
Sample call:
exec stp_customers_insert 'ram', '674673932', '122', '5th cross', 'trichy', 'tamilnadu', 620001
I get this error:
Msg 8114, Level 16, State 5, Procedure stp_customers_insert, Line 23
Error converting data type varchar to int.
The problem appears to be that your stored procedure expects 8 parameters:
stp_customers_insert(#customerid int, #name varchar(50), #phone varchar(50),
#doorno varchar(50), #streetname varchar(50), #city varchar(50),
#state varchar(50), #zip int)
but you are only passing 7 parameters when you actually call the proc:
exec stp_customers_insert 'ram','674673932','122','5th cross','trichy','tamilnadu',620001
If you don't know or don't want to perform the duplicate check on the CustomerID, then you could slightly modify your call to just pass NULL:
exec stp_customers_insert NULL, 'ram','674673932','122','5th cross','trichy','tamilnadu',620001
As an aside, if the proc is not even inserting the CustomerID, and this field is auto increment, then I don't see the point of passing it. Instead, you might want to consider using a unique constraint to achieve the same.
exec stp_customers_insert 1,'ram','674673932','122','5thcross','trichy','tamilnadu',620001
You have to pass #customerid value in procedure parameters - then it will execute without error.
In your table structure CustomerID is defined as INT. But as your stored procedure is defined in this format:
stp_customers_insert(#customerid int,#name ....
You are sending ram as value for customerid in
exec stp_customers_insert 'ram','674673932'....
Correct this to:
exec stp_customers_insert '*enter the CustId value here*','ram','674673932'....
Replace *enter the CustId value here* with the CustomerID
Also change:
insert into Customers(Name,PhoneNumber,DoorNo,StreetName,City,Statee,Zipcode) values(#name,#phone,#doorno,#streetname,#city,#state,#zip)
To include CustomerID as:
insert into Customers(CustomerID,Name,PhoneNumber,DoorNo,StreetName,City,Statee,Zipcode) values(#customerid,#name,#phone,#doorno,#streetname,#city,#state,#zip)
I suggest remove #customerid from sp CustomerID is auto increment field so no need to pass any value for CustomerID. It should be like this:
alter procedure stp_customers_insert(#name varchar(50),#phone varchar(50),#doorno varchar(50),#streetname varchar(50),#city varchar(50),#state varchar(50),#zip int)
as
begin
if exists(select CustomerID from Customers where Name = #name ,phone = #phone ,doorno = #doorno ,streetname = #streetname ,city= #city,state= #state , zip = #zip )
begin
raiserror('employee id already exists',1,1)
end
else
begin
insert into Customers(Name,PhoneNumber,DoorNo,StreetName,City,Statee,Zipcode) values(#name,#phone,#doorno,#streetname,#city,#state,#zip)
end
end
exec stp_customers_insert 'ram','674673932','122','5th cross','trichy','tamilnadu',620001

Error converting data type varchar to int error in stored procedure

My stored procedure is
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[Customer_Registrations]
#type varchar(50) = null,
#Customer_ID int = null,
#Customer_Name varchar(50) = null,
#Email varchar(50) = null,
#Password varchar(50) = null,
#Mobile varchar(50) = null
AS
BEGIN
SET NOCOUNT ON;
IF #type = 'select'
BEGIN
SELECT *
FROM ssshub..Customer_Master
END
IF #type = 'specific'
BEGIN
SELECT *
FROM ssshub..Customer_Master
WHERE Customer_ID = #Customer_ID
END
IF #type = 'insert'
BEGIN
INSERT INTO [dbo].[Customer_Master]([Customer_Name], [Email],[Password], [Mobile], [SDate])
VALUES ('#Customer_Name', '#Email', '#Password', '#Mobile', CURRENT_TIMESTAMP)
END
END
And my table
This is working fine
This query works fine but when I am trying to insert it using stored procedure it throws an error.
I have an identity specification for customer_id on so no need to insert it
INSERT INTO [dbo].[Customer_Master] ([Customer_Name], [Email], [Password], [Mobile], [SDate])
VALUES('ewcewc', 'dewdw#dwc.com', 'dewdwd', '9999999999', CURRENT_TIMESTAMP)
Now when I am trying to execute my stored procedure with the following statement
exec customer_registrations 'insert', 'dsad', 'test#test.com', 'pass', '9999900000'
I get:
Error converting data type varchar to int
Lining up your arguments with the parameters:
'insert' -> #type varchar(50)
'dsad' -> #Customer_ID int
'test#test.com' -> #Customer_Name varchar(50)
'pass' -> #Email varchar(50)
'9999900000' -> #Password varchar(50)
-> #Mobile varchar(50) = null
...you can see that 'dsad' has no way of being understood as an int. Maybe there's a problem elsewhere as well, but at the very least, the stored procedure is not being called correctly.
Update:
If your intent was to omit some arguments that aren't relevant in a certain case, you have to use named parameters; otherwise, arguments can only be applied in the same order the parameters appear:
exec customer_registrations
'insert',
#Customer_Name = 'dsad',
#Email = 'test#test.com',
#Password = 'pass',
#Mobile = '9999900000';
Please pass null value in procedure while you insert the data in table. Run the procedure below way while inserting data in table. you should me manage all the parameter of procedure. you are not passed value of Customer_ID, so that's way error occur.
EXEC [dbo].[Customer_Registrations] 'insert',null,'ewcewc', 'dewdw#dwc.com', 'dewdwd', '9999999999'
Create Database Test
Create Table Employee
(
EmpId int identity(1,1) not null primary Key,
EmpName varchar(50),
Address varchar(50),
MobileNo int
)
Select * From [dbo].[Employee]
Alter Table [dbo].[Employee] Alter Column MobileNo Bigint
Insert into [dbo].[Employee] values('Harsh Kumar','Banglore','9748342075')
Create Proc MyProc
As
Select * From [dbo].[Employee]
EXEC MyProc
Create Proc SP_GetEmp
#EmpId int,
#EmpName varchar(50),
#Address varchar(50),
#MobileNo int
As
Insert into [dbo].[Employee](EmpId, EmpName, Address, MobileNo) Values(#EmpId, #EmpName, #Address, #MobileNo)
EXEC SP_GetEmp 'Rahul Kr','Pune', 8250707544
EXEC MyProc
Error:- Error converting data type varchar to int.

Why Ident_Current returns null but Scope_Identity does?

It returns null, why? The IDENT_CURRENT part but it works well with Scope_Identity, why ?
ALTER PROCEDURE [dbo]. [InsertComplaints]
#ComplaintCode varchar(50),
#ComplaintType_ID smallint,
#RecievingMode_ID smallint,
#Subject varchar(100),
#ComplainantID smallint,
#District_ID smallint,
#AddressedTo varchar(50),
#DiaryNo varchar(50),
#User_ID int,
#Status_ID smallint,
#RecievedDate smalldatetime,
#IGRemarks varchar(MAX) = null,
#PsoRemarks varchar(MAX) =null,
#FinalDecision varchar(250)=null,
#AgainstDist_ID smallint,
#HomePS_ID smallint,
#AgainstPS_ID smallint,
#Name varchar(75),
#DesigID int,
#ForwardedBy smallint,
#SMS_ID int = 0,
#result bit output,
#ID int output
AS
BEGIN
Begin Try
insert into dbo.Complaints
values (
#ComplaintCode,
#ComplaintType_ID,
#RecievingMode_ID ,
#Subject,
#ComplainantID ,
#District_ID ,
#AddressedTo ,
#DiaryNo,
#User_ID,
#Status_ID,
#RecievedDate,
#IGRemarks,
#PsoRemarks,
#FinalDecision,
#AgainstDist_ID,
#HomePS_ID,
#AgainstPS_ID,
#Name ,
#DesigID,
#ForwardedBy,
#SMS_ID
)
Set #result = ##ROWCOUNT
Set #ID = IDENT_CURRENT('ComplaintID') --SCOPE_IDENTITY()
Select #ID
End Try
Begin Catch
Set #result=0
End Catch
END
I want to get a last inserted id from particular table such that complaintID from complaints table but it doesn't return any but null. Help !
According to msdn the IDENT_CURRENT function will return null if the calling user does not have enough permissions on this object.
Another possibility is that your object name is wrong, i see you're doing your insert with the dbo prefix. Maybe that will help.

SQL problem: same column in one

hy!
I have 2 tables and in each I have a column date, I need to make a single table with the information from all 2 tables with a column date which i want to get from the 3 tables,but in the same column
i tried the following code, but didn`t work
CREATE FUNCTION dbo.GetContactInformation(#id int)
RETURNS #retActivityInformation TABLE
(
ClientID int NOT NULL,
ActivityDate datetime NULL,
Tipe nvarchar(50) NULL,
Number nvarchar(50) NULL,
Value int NULL,
Statu nvarchar(50) NULL,
PRIMARY KEY CLUSTERED (clientID ASC)
) AS
BEGIN
DECLARE
#ClientID int,
#ActivityDate datetime,
#Tip nvarchar(50),
#Number nvarchar(50),
#Value int,
#Statu nvarchar(50);
SELECT
#ClientID = ClientID,
#ActivityDate = ActivityDate,
#Number = Number,
#Value = Value,
#Statu = Statu
FROM Fa,Pay
WHERE ID = #id;
SET #ActivityDate =
CASE
WHEN EXISTS(SELECT Fa.DataEmitere FROM Fa AS e
WHERE e.ID = #id)
THEN 'Fa'
WHEN EXISTS(SELECT Pay.Data FROM Pay AS bec
WHERE bec.ID = #id)
THEN 'Pay'
END;
IF #id IS NOT NULL
BEGIN
INSERT #retActivityInformation
SELECT #clientID, #ActivityDate, #Number, #Value,#Statu;
END;
RETURN;
END;
Just prefix the field with the database name. I am going to assume the date you actually mean is ActivityDate. If you want to SELECT/INSERT using this field you will need to prefix with Fa or Pay so it would be Fa.ActivityDate or Pay.ActivityDate.
If this is not the field then we'd need more info.
Use the column by specifying the table name as below:-
CREATE FUNCTION dbo.GetContactInformation(#id int)
RETURNS #retActivityInformation TABLE
(
ClientID int NOT NULL,
ActivityDate datetime NULL,
Tipe nvarchar(50) NULL,
Number nvarchar(50) NULL,
Value int NULL,
Statu nvarchar(50) NULL,
PRIMARY KEY CLUSTERED (clientID ASC)
) AS
BEGIN
DECLARE
#ClientID int,
#ActivityDate datetime,
#Tip nvarchar(50),
#Number nvarchar(50),
#Value int,
#Statu nvarchar(50);
SELECT
#ClientID = ClientID,
#ActivityDate = Fa.ActivityDate,
#Number = Number,
#Value = Value,
#Statu = Statu
FROM Fa,Pay
WHERE ID = #id;
SET #ActivityDate =
CASE
WHEN EXISTS(SELECT Fa.DataEmitere FROM Fa AS e
WHERE e.ID = #id)
THEN 'Fa'
WHEN EXISTS(SELECT Pay.Data FROM Pay AS bec
WHERE bec.ID = #id)
THEN 'Pay'
END;
IF #id IS NOT NULL
BEGIN
INSERT #retActivityInformation
SELECT #clientID, #ActivityDate, #Number, #Value,#Statu;
END;
RETURN;
END;
See the middle part here:
CREATE FUNCTION dbo.GetContactInformation(#id int)
RETURNS #retActivityInformation TABLE
(
ClientID int NOT NULL,
ActivityDate datetime NULL,
Tipe nvarchar(50) NULL,
Number nvarchar(50) NULL,
Value int NULL,
Statu nvarchar(50) NULL,
PRIMARY KEY CLUSTERED (clientID ASC)
) AS
BEGIN
DECLARE
#ClientID int,
#ActivityDate datetime,
#Tip nvarchar(50),
#Number nvarchar(50),
#Value int,
#Statu nvarchar(50);
SELECT
#ClientID = ClientID,
#ActivityDate = ActivityDate,
#Number = Number,
#Value = Value,
#Statu = Statu
FROM Fa,Pay
WHERE ID = #id;
SET #ActivityDate = ISNULL(
(SELECT top 1 Fa.DataEmitere FROM Fa AS e WHERE e.ID = #id),
(SELECT top 1 Pay.Data FROM Pay AS bec WHERE bec.ID = #id))
IF #id IS NOT NULL
BEGIN
INSERT #retActivityInformation
SELECT #clientID, #ActivityDate, #Number, #Value,#Statu;
END;
RETURN;
END;
Essentially, instead of testing to see if the data EXISTS just to get the field name, get the data directly.

Return NEWSEQUENTIALID() as an output parameter

Imagine a table that looks like this:
CREATE TABLE [dbo].[test](
[id] [uniqueidentifier] NULL,
[name] [varchar](50) NULL
)
GO
ALTER TABLE [dbo].[test] ADD CONSTRAINT [DF_test_id] DEFAULT (newsequentialid()) FOR [id]
GO
With an INSERT stored procedure that looks like this:
CREATE PROCEDURE [Insert_test]
#name as varchar(50),
#id as uniqueidentifier OUTPUT
AS
BEGIN
INSERT INTO test(
name
)
VALUES(
#name
)
END
What is the best way to get the GUID that was just inserted and return it as an output parameter?
Use the Output clause of the Insert statement.
CREATE PROCEDURE [Insert_test]
#name as varchar(50),
#id as uniqueidentifier OUTPUT
AS
BEGIN
declare #returnid table (id uniqueidentifier)
INSERT INTO test(
name
)
output inserted.id into #returnid
VALUES(
#name
)
select #id = r.id from #returnid r
END
GO
/* Test the Procedure */
declare #myid uniqueidentifier
exec insert_test 'dummy', #myid output
select #myid
Try
SELECT #ID = ID FROM Test WHERE Name = #Name
(if Name has a Unique constraint)