Help with an IF in SQL SERVER Stored procedure - sql-server

can anyone help me with construction of an IF in a stored procedure in sql server.
Basically I have a simple stored procedure but I now need to pass in a new input parameter which depending if it is true I pass the value D and if its false I pass the value A. But the change is in the middle of a subquery.. let me explain... here is the stored procedure. basically if I send in True for ReturnOldStatus I execute the subquery ItemStatus='D' and if it is false then i pass in ItemStatus='A'
CREATE PROCEDURE [dbo].[MyTempStoredProc]
(
#IdOffice Int,
#ReturnOldStatus bit
)
AS
BEGIN
SET NOCOUNT ON;
SELECT * FROM Offices
WHERE
IdOffice = #IdOffice
AND (V.OffType NOT IN (
SELECT * FROM MiscOff
WHERE
ItemStatus= 'D') // This needs to be ItemStatus ='A' if FALSE is passed in on the input param
Any ideas??
Thanks

I would solve it like this:
declare #itemStatus varchar(1);
if (#inputParam = 'FALSE')
begin
set #itemStatus = 'A'
end
else
set #itemStatus = 'D'
SELECT * FROM Offices
WHERE
IdOffice = #IdOffice
AND (V.OffType NOT IN (
SELECT * FROM MiscOff
WHERE ItemStatus= #itemStatus)
)
T-Sql is not my native language, so there may be errors in there...

Just use the T-SQL if statement:
IF #ReturnOldStatus = 0
BEGIN
--Some statements
END
ELSE
BEGIN
--Some other statements
END

I think this will suffice for your problem. If not, look into the DECLARE/SET statements in TSQL.
CREATE PROCEDURE [dbo].[MyTempStoredProc]
(#IdOffice Int,
#ReturnOldStatus bit )
AS BEGIN
SET NOCOUNT ON;
SELECT * FROM Offices
WHERE IdOffice = #IdOffice
AND (V.OffType NOT IN (SELECT * FROM MiscOff
WHERE (ItemStatus= 'D' AND #ReturnOldStatus = 1)
OR
(ItemStatus= 'A' AND #ReturnOldStatus = 0)
)

Related

Combined Procedure for Triggers

How would I create a stored procedure that is capable of taking in a flag value such as (1,2,3) where 1=insert, 2=delete, 3=update.
So for example if flag is 1, the procedure will do insert, and so forth.
I know how to create stored procedures and have already made and tested my triggers, but I can't find any examples of this and dont know where to start.
Thanks.
You can use normal If else statement:
CREATE PROCEDURE <ProcedureName> (#Flag int)
AS
BEGIN
IF(#Flag = 1)--INSERT
BEGIN
<Insert statement>
END
ELSE IF(#Flag = 2) --DELETE
BEGIN
<Delete statement>
END
ELSE IF (#Flag = 3) --UPDATE
BEGIN
<Update statement>
END
END
GO
I would use CTEs and conditions.
To give you an example of what I mean:
CREATE OR REPLACE FUNCTION public.test (_flag integer) RETURNS void AS
$func$
WITH delete AS
(DELETE FROM
atable
WHERE
_flag = 1),
insert AS
(INSERT INTO
atable (acolumn)
SELECT
'Hello World'
WHERE
_flag = 2)
UPDATE
atable
SET
acolumn = 'Hello World'
WHERE
_flag = 3;
$func$
LANGUAGE sql COST 100 STRICT;
You'll notice each statement has its own flag-checking condition.

Insert and update stored procedure with parameters and default of zero doesn't work

I need help to create an insert stored procedure with parameters, if pass the value for that parameter, then it has to insert or update in database, else it should use a default of zero.
My problem is that when I execute the code below using a SampleID = 0, it works... any other SampleID does nothing.
Thanks in advance
Execution of the stored procedure:
SET NOCOUNT OFF
EXEC SP_Samples '0', '3' ,'Pink'
GO
Stored procedure code:
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[SP_Samples]
(#SamplesID int,
#SamplesCategoriesID int,
#SamplesName nvarchar(50)
)
AS
BEGIN
SET NOCOUNT ON;
IF (#SamplesID = 0)
BEGIN
INSERT INTO tblSamples ([SamplesName], [SamplesCategoriesID])
VALUES (#SamplesName, #SamplesCategoriesID)
END
ELSE
BEGIN
UPDATE [tblSamples]
SET SamplesCategoriesID = #SamplesCategoriesID,
SamplesName = #SamplesName
WHERE SamplesID = #SamplesID
END
END
First, you have to learn how to debug a stored procedure.
Just temporarily insert following code into your procedure:
SELECT #SamplesID, #SamplesCategoriesID, #SamplesName;
That is how you will make sure values passed correctly.
Second, for Non-zero cases add following statement:
SELECT COUNT(*) FROM tblSamples WHERE SamplesID = #SamplesID;
That statement should not return zero.
Third, to be 500% sure you are doing it right, pass parameters by name like this:
EXEC SP_Samples #SamplesID = 0, #SamplesCategoriesID = 3, #SamplesName = 'Pink';
GO
EXEC SP_Samples #SamplesID = 1, #SamplesCategoriesID = 4, #SamplesName = 'Blue';
GO

T-SQL different result between code in stored and same code in query pane

I'm working on a procedure that should return a o or a 1, depending on result from parameter calculation (parameters used to interrogate 2 tables in a database).
When I excute that code in a query pane, it gives me the results i'm expecting.
code looks like:
SELECT TOP 1 state, updDate INTO #history
FROM [xxx].[dbo].[ImportHystory] WHERE (db = 'EB') ORDER BY addDate DESC;
IF (SELECT state FROM #history) = 'O'
BEGIN
SELECT TOP 1 * INTO #process_status
FROM yyy.dbo.process_status WHERE KeyName = 'eb-importer';
IF(SELECT s.EndDate FROM #process_status s) IS NOT NULL
IF (SELECT s.EndDate FROM #process_status s) > (SELECT h.updDate FROM #history h)
BEGIN
IF (SELECT MessageLog from #process_status) IS NOT NULL SELECT 1;
ELSE SELECT 0;
END
ELSE
SELECT 1;
ELSE
SELECT 1;
END
ELSE
SELECT 0
I'm in the situation where EndDate from #process_status is null, so the execution returns 1.
Once i put the SAME code in a SP, and pass 'EB' and 'eb-importer' as parameters, it returns 0.
And I exec the procedure with the data from the table right in front of me, so i know for sure that result is wrong.
Inside the procedure:
ALTER PROCEDURE [dbo].[can_start_import] (#keyName varchar, #db varchar, #result bit output)
DECLARE #result bit;
and replace every
SELECT {0|1}
with
SELECT #result = {0|1}
Executed from the Query pane:
DECLARE #result bit;
EXEC [dbo].[can_start_import] #KeyName = 'eb-importer', #db = 'EB', #result = #result OUTPUT
SELECT #result AS N'#result'
Why does this happen?
You are doing a top(1) query without an order by. That means SQL Server can pick any row from table1 that matches the where clause.
If you want to guarantee that the result is the same every time you execute that code you need an order by statement that unambiguously orders the rows.
So, apparently 2 things needed to be done:
set the length of the varchar parameter with a higher length,
filter with ' like ' instead of ' = ' for god knows what reason
Now it work as i expected to do, but i still don't get the different results between the query pane and the procedure if i use the equal...

Sql Server Stored procedure returns -1

I am writing code on entity framework 6.0, linq on asp.net, sql server platform.
I've written a stored procedure which supposed to return an output value (0 or 1)
Firstly I wrote SP by using output parameter as follows:
ALTER proc [dbo].[checkUser]
(
#oNo int,
#pw varchar(50),
#val int output
)
as
begin
if EXISTS (select * from Users where #oNo=sNo and #pw=password)
begin
set #val=1
end
if not exists(select * from Users where #oNo=sNo and #pw=password)
begin
set #val=0
end
end
Didnt work. It returned -1. Then I changed SP like this:
ALTER proc [dbo].[checkUser]
(
#oNo int,
#pw varchar(50)
)
as
begin
if EXISTS (select * from Users where #oNo=sNo and #pw=password)
begin
return 1
end
else
begin
return 0
end
end
Each ways stored procedure returns only -1
Can you help me please, where am i doing wrong?
Try to replace "return" by "select".
if EXISTS (select * from Users where #oNo=sNo and #pw=password)
begin
select 1
end
else
begin
select 0
end

Efficiently return a value from a stored procedure

I have query which returns single value (i.e) count. I'm exceuting it using the stored procedure in the following way and using execute reader with dataset to get single value
CREATE PROCEDURE GetCnt
#EmpNo char(4)
AS
BEGIN
SET NOCOUNT ON;
Declare #Cnt int
SELECT #Cnt = count(*)
FROM employees
WHERE EMPLNO = #EmpNo
AND test = 'p'
BEGIN
SELECT #Cnt
END
END
is this effcient way
or Do I need to use the execute.scalar() and return value directly from the query instead of assigning to #cnt
can any one advise me
All ExecuteScalar does is get the first field from the first record.
Can't you just SELECT the count directly?
BEGIN
SET NOCOUNT ON
SELECT Count(*) FROM employees WHERE EMPLNO = #EmpNo AND test='p'
END
You do not need to create the variable. You just need the following:
CREATE PROCEDURE GetCnt
#EmpNo char(4)
AS
BEGIN
SET NOCOUNT ON;
SELECT count(1)
FROM employees
WHERE EMPLNO = #EmpNo
AND test = 'p'
END
Since this is only one value being returned from the stored procedure, you will likely want to use ExecuteScalar()

Resources