Stored Procedure Fill Variable with a ResultSet of a Query - sql

I have a little Problem but don't know the Solution!
I have wrote a Stored Procedure. The function of this isn't necessary.
I want to declare a Variable from Type int.
This Variable must get the Value of a SQL Query.
My attempt:
DECLARE #ParentServiceProviderId int = null
SET #ParentServiceProviderId = (SELECT ParentServiceProviderId
FROM ServiceProvider
WHERE ServiceProviderId = #ServiceProviderId)
It didn't work! The ResultSet of the Query have one Row every Time!
I don't know how to solve this Problem!
Here is the complete Stored Procedure:
ALTER PROCEDURE [dbo].[InsertCarmakerPartnership_ChildToParent]
#ServiceProviderId int,
#CarmakerId int,
#ValidFrom datetime,
#ValidTo datetime
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
DECLARE #parentSPPId int, #parentSPPParentId int, #superParentId int, #ParentServiceProviderId int = null
SET #ParentServiceProviderId = (SELECT ParentServiceProviderId
FROM ServiceProvider
WHERE ServiceProviderId = #ServiceProviderId)
DECLARE ServiceProviderParent_Cursor CURSOR FOR
SELECT ServiceProviderId, ParentServiceProviderId
FROM ServiceProvider
WHERE ServiceProviderId = #ParentServiceProviderId
OPEN ServiceProviderParent_Cursor;
FETCH NEXT FROM ServiceProviderParent_Cursor INTO #parentSPPId, #parentSPPParentId
IF (#ParentServiceProviderId is NULL)
BEGIN
SET #superParentId = #ServiceProviderId
EXEC InsertCarmakerPartnership_ParentToChild #superParentId, #CarmakerId, #ValidFrom, #ValidTo;
END
WHILE ##FETCH_STATUS = 0
BEGIN
IF #ServiceProviderId > 0
BEGIN
EXEC InsertCarmakerPartnership_ChildToParent #parentSPPId, #CarmakerId, #parentSPPParentId, #ValidFrom, #ValidTo ;
IF (SELECT COUNT(*) FROM dbo.CarmakerPartnership WHERE ServiceProviderId = #parentSPPId AND CarmakerId = #CarmakerId AND IsDeleted = 0) = 0
BEGIN
INSERT INTO dbo.CarmakerPartnership (CarmakerId, ServiceProviderId, CreatedBy, ChangedBy, ValidityPeriodFrom, ValidityPeriodTo) VALUES (#CarmakerId, #parentSPPId, SYSTEM_USER, SYSTEM_USER, #ValidFrom, #ValidTo)
END
END
FETCH NEXT FROM ServiceProviderParent_Cursor INTO #parentSPPId, #parentSPPParentId
END;
CLOSE ServiceProviderParent_Cursor;
DEALLOCATE ServiceProviderParent_Cursor;
END
Thanks for your help and sorry for my bad english!
Best regards.

Anyway, use next code to populate a variable:
DECLARE #ParentServiceProviderId int
SELECT #ParentServiceProviderId = ParentServiceProviderId
FROM ServiceProvider
WHERE ServiceProviderId = #ServiceProviderId

do not assign default value to this variable and the rest of the code is:
DECLARE #ParentServiceProviderId int
SELECT #ParentServiceProviderId = ParentServiceProviderId
FROM ServiceProvider
WHERE ServiceProviderId = #ServiceProviderId

Related

Can not write the value to a variable

I have a function, which needs to return true if there is a row in a table with values which user inputs.
I need to write the value to a variable which Ii return, but I got an error:
Incorrect syntax near '#ret'.
USE BDLab5;
GO
Create Function WasComplaint (#date date, #component varchar)
Returns BIT
Begin
Declare #was int, #ret bit
Select #was = ComponentCode from Complaints
Where ComplaintDate = #date AND
ComponentCode = (Select ComponentCode from Components Where ComponentName = #component)
if (#was = 0)
#ret = 0
else
#ret = 1
Return #ret
End;
I tried different variant of if else syntax but it doesn't help.
You need to use SET when assigning a value to a variable.
USE BDLab5;
GO
Create Function WasComplaint (#date date, #component varchar)
Returns BIT
Begin
Declare #was int, #ret bit
Select #was = ComponentCode from Complaints
Where ComplaintDate = #date AND
ComponentCode = (Select ComponentCode from Components Where ComponentName = #component)
if (#was = 0)
set #ret = 0
else
set #ret = 1
Return #ret
End;
Put the word SET before #ret when you give it a value

How to get stored procedure internal Declare Variable value in SQL Server

This is my stored procedure:
CREATE PROCEDURE MYSP
(#PARAM INT,
#PARAM2 NVARCHAR(34),
#OUTPARAM3 NVARCHAR(34) OUTPUT)
AS
BEGIN
DECLARE #RParam INT
DECLARE #ErrParam2 NVARCHAR(34)
IF(#PARAM = 1 AND #PARAM2 = 'abc' )
BEGIN
SET #OUTPARAM3 = 'EQUAL'
SET #RPARAM = 0
END
ELSE
BEGIN
SET #ERRPARAM2 = 'SOME ERROR..MSG'
SET #RPARAM = -1
END
RETURN #RPARAM
END
And I am trying to get the value of the internally declare variable value.
DECLARE #RParam INT
DECLARE #ErrParam2 NVARCHAR(34)
#RParam is returned but how can I return #ErrParam2 value?
Declare #RP int
Declare #ErrMsg Nvarchar(40)
Exec #RP = MYSP 1,'abc'
You need to specify the output parameter both when the stored procedure is defined and when it is called:
Declare #RP int;
Declare #ErrMsg Nvarchar(40);
Exec #RP = MYSP 1, 'abc' , #ErrMsg output;

How to output the results of a stored procedure with a while loop MS SQL Server?

I'm performing some calculations on tsunami's wave time between different radii. I'm having trouble outputting the results of the stored procedure into a table. The output I get is a blank table without any data stored. The log says "0 rows affected". For some reason my inputs and outputs are not registering. I thinking it could have something to do with the way I'm using the loop inside to SP.
CREATE PROCEDURE SP_Tsunami
(
#oceanDepth int,
#radii1 int,
#radii2 int,
#tsunamiSpeed int OUTPUT,
#tsunamiTimeDifference int OUTPUT
)
AS
BEGIN
SET #tsunamiSpeed = sqrt(32.1725 * #oceanDepth) * (60.0/88.0);
Truncate Table dbo.Tsunami
DECLARE #i int
SET #i = 0;
WHILE (#i <= 10000)
BEGIN
INSERT INTO dbo.Tsunami (Radius, Wavetime)
VALUES
(#i, (#i / #tsunamiSpeed))
SET #i = #i + 100;
END
DECLARE #tsunamiTime1 int
DECLARE #tsunamiTime2 int
SET #tsunamiTime1 = (Select Wavetime From Tsunami WHERE Radius = #radii1);
SET #tsunamiTime2 = (Select Wavetime From Tsunami WHERE Radius = #radii2);
SET #tsunamiTimeDifference = (#tsunamiTime2 - #tsunamiTime1);
END
/* Outputs */
DECLARE #Out_tsunamiSpeed int
DECLARE #Out_tsunamiTimeDifference int
/* Inputs */
DECLARE #IN_oceanDepth int
DECLARE #IN_radii1 int
DECLARE #IN_radii2 int
SET #IN_oceanDepth = 15088;
SET #IN_radii1 = 2500;
SET #IN_radii2 = 7500;
Execute SP_Tsunami #oceanDepth = #IN_oceanDepth, #radii1 = #IN_radii1, #radii2 = #IN_radii2, #tsunamiSpeed = #Out_tsunamiSpeed OUTPUT, #tsunamiTimeDifference = #Out_tsunamiTimeDifference OUTPUT
Doesn't make much sense to insert the data into table and then read it from there. All the rows you are inserting into your table eventually only one row is being read from the table to assign values to variables.
Also change the procedure name prefix from sp_ to something else, sp_ is system stored procedure prefix.
I have changed the procedure definition a little bit hope it makes sense.
ALTER PROCEDURE SP_Tsunami
(
#oceanDepth int,
#radii1 int,
#radii2 int,
#tsunamiSpeed int OUTPUT,
#tsunamiTimeDifference int OUTPUT
)
AS
BEGIN
SET #tsunamiSpeed = sqrt(32.1725 * #oceanDepth) * (60.0/88.0);
DECLARE #tsunamiTime1 int
DECLARE #tsunamiTime2 int
SET #tsunamiTime1 = #radii1 / #tsunamiSpeed;
SET #tsunamiTime2 = #radii2 / #tsunamiSpeed;
SET #tsunamiTimeDifference = (#tsunamiTime2 - #tsunamiTime1);
END
GO
Execute the procedure with your provided data.
/* Outputs */
DECLARE #Out_tsunamiSpeed int
DECLARE #Out_tsunamiTimeDifference int
/* Inputs */
DECLARE #IN_oceanDepth int
DECLARE #IN_radii1 int
DECLARE #IN_radii2 int
SET #IN_oceanDepth = 15088;
SET #IN_radii1 = 2500;
SET #IN_radii2 = 7500;
Execute SP_Tsunami #oceanDepth = #IN_oceanDepth
, #radii1 = #IN_radii1
, #radii2 = #IN_radii2
, #tsunamiSpeed = #Out_tsunamiSpeed OUTPUT
, #tsunamiTimeDifference = #Out_tsunamiTimeDifference OUTPUT
SELECT #Out_tsunamiSpeed AS Out_tsunamiSpeed
,#Out_tsunamiTimeDifference AS Out_tsunamiTimeDifference
Result Set:
Out_tsunamiSpeed Out_tsunamiTimeDifference
475 10

Problems with ROLLBACK TRANSACTION inside try/catch

I'm having this error when I try to execute this code:
Transaction count after EXECUTE indicates a mismatching number of BEGIN and COMMIT statements. Previous count = 0, current count = 1.
I know the problem is on the sp [dbo].[QueueInsert], the sp has an error and it goes directly to the catch. It's funny because the first one (EXEC [dbo].[BacthInsert]) is inserting a summary record and after running the sp, I see the record, so is doing a commit and not doing a rollback. What's wrong with this code? thanks!
CREATE PROCEDURE [cnfg].[SendEmail]
(
,#Employees [dbo].[Employees] readonly
,#ApplicationName NVARCHAR(256)
,#ErrorMsg NVARCHAR(300) = NULL OUTPUT
)
AS
BEGIN
DECLARE #ReturnVal INT
DECLARE #ApplicationId UNIQUEIDENTIFIER
DECLARE #NewIdBatch INT
DECLARE #ID INT
DECLARE #EmployeeId INT
DECLARE #Index INT = 1
DECLARE #Total INT
SET NOCOUNT ON;
SET XACT_ABORT ON;
SET #ReturnVal = 0;
SET #ErrorMsg = '';
SET #ApplicationId = [GetId](#ApplicationName);
IF (#ApplicationId IS NULL)
BEGIN
SET #ReturnVal = 1;
SET #ErrorMsg = 'The Application Name does not exist in the database';
Goto ProcedureExit
END
----------------------------------------------------------
BEGIN TRY -- Start Main TRY
----------------------------------------------------------
BEGIN TRANSACTION;
EXEC [dbo].[BacthInsert]
#ParameterId = 1
,#ID = #NewSendEmailBatchId OUTPUT
,#ErrorMsg = #ErrorMsg OUTPUT
IF ( #ErrorMsg <> '' )
BEGIN
SET #ReturnVal = 1;
SET #ErrorMsg = 'There was an error trying to insert data into [dbo].[BacthInsert] table';
RAISERROR(#ErrorMsg, 16, 1)
END
SELECT ROW_NUMBER() OVER ( ORDER BY EmployeeId ) Row,
EmployeeId
INTO #EmpIds
FROM #Employees
SELECT #Total = COUNT(*) FROM #EmpIds
WHILE ( #Index <= #Total )
BEGIN
SELECT #EmployeeId=EmployeeId FROM #EmpIds WHERE Row = #Index
EXEC [dbo].[QueueInsert]
#SendEmailBatchId = #NewIdBatch
,#ID = #ID OUTPUT
,#ErrorMsg = #ErrorMsg OUTPUT
IF ( #ErrorMsg <> '' )
BEGIN
SET #ReturnVal = 1;
SET #ErrorMsg = 'There was an error trying to insert data into [dbo].[QueueInsert] table';
RAISERROR(#ErrorMsg, 16, 1)
END
SET #Index+=1;
END
COMMIT TRANSACTION;
----------------------------------------------------------
END TRY -- End Main TRY
----------------------------------------------------------
----------------------------------------------------------
BEGIN CATCH -- Start Main CATCH
----------------------------------------------------------
SELECT ERROR_MESSAGE()
IF (XACT_STATE()) = -1
BEGIN
ROLLBACK TRANSACTION;
END;
----------------------------------------------------------
END CATCH -- End Main CATCH
----------------------------------------------------------
ProcedureExit:
RETURN #ReturnVal;
END

sql server The multi-part identifier " " could not be bound stored procedure

I create a stored procedure in which I call two functions .
I'm getting an error:
Msg 4104, Level 16, State 1, Procedure Add_Translation, Line 25
The multi-part identifier ".word" could not be bound.
This is my stored procedure:
ALTER PROCEDURE [dbo].[Add_Translation]
#english nvarchar(70),
#kurdish nvarchar(70),
#english_category int,
#kurdish_category int,
#result int out
AS
BEGIN
SET NOCOUNT ON;
if #english is not null and #kurdish is not null and #english_category is not null and #kurdish_category is not null
begin
declare #intEnId int=-1;
exec #intEnId = Check_English_word #text = #english;
declare #identityEnglish int;
declare #identityKurdish int;
if #intEnId = -1
begin
insert into english_table values(#english, #english_category);
set #identityEnglish = SCOPE_IDENTITY();
end
else
begin
set #identityEnglish = (select e.english_id from english_table e where UPPER(.word)=UPPER(#english));
end
declare #intKuId int=-1;
exec #intKuId=Check_Kurdish_Word #word=#kurdish;
if #intKuId =-1
begin
insert into kurdish_table values(#kurdish, #kurdish_category);
set #identityKurdish = SCOPE_IDENTITY();
end
else
begin
set #identityKurdish = (select k.kurdish_id from kurdish_table k where upper(k.word)=upper(#kurdish));
end
declare #translated int =0;
exec #translated = Check_Translation #english_id = #identityEnglish, #kurdish_id = #identityKurdish;
if #translated=0
begin
insert into transactions values(#identityEnglish, #identityKurdish);
set #result = 1;
end
else
begin
set #result = 2;
end
end
else
begin
set #result = 0;
end
END
Here is the first function:
ALTER FUNCTION [dbo].[Check_English_word]
(
#text nvarchar(70)
)
RETURNS int
AS
BEGIN
DECLARE #Result int
set #Result=-1;
if #text is not null
begin
SELECT #Result = e.english_id
from english_table e
where UPPER(e.word) = UPPER(#text);
end
RETURN #Result
END
Second function:
ALTER FUNCTION [dbo].[Check_Kurdish_Word]
(
#word nvarchar(70)
)
RETURNS int
AS
BEGIN
DECLARE #Result int
set #Result=-1;
if #word is not null
begin
SELECT #Result = k.kurdish_id
from kurdish_table k
where UPPER(k.word) = UPPER(#word);
end
RETURN #Result
END
You are missing an e in this line
set #identityEnglish=(select e.english_id from english_table e
where UPPER(.word)=UPPER(#english));
Change it to
set #identityEnglish=(select e.english_id from english_table e
where UPPER(e.word)=UPPER(#english));
Also, it is good practice to specify columns when doing an insert -
ie
insert into english_table values(#english,#englsih_category);
should be
insert into english_table (word, category) values(#english,#englsih_category);