Nested if in SQL Server - database

this is my query :
if (a)
begin
---
---
---
if (b)
---
else
---
end
when I remove 3 lines of this query ( line 6 and 7 and 8 ), it works ,, what's wrong with that query when I have all the lines
I should say the line 7 is just this : "return -23" and the line 9 is just this : delete tablename where ..
I mean as I know the second If doesn't need begin and end (?)
my main query is this :
if #Updatekind = 2
BEGIN
Delete SALFactorAddOns
Where SerialNoFhsFAO = #SerialNoFHS
and (CompanyNo = #CompanyNoFHS)
if ((select invsnfhs from SALFactorHds where (SerialNoFHS = #SerialNoFHS)
and (CompanyNo = #CompanyNoFHS) ) > 0 )
return -23
else
DELETE SALFactorHds
WHERE (SerialNoFHS = #SerialNoFHS)
and (CompanyNo = #CompanyNoFHS)
end

An If statement go with keywords BEGIN and END (statement block), if there is no statement block used, the IF or ELSE condition can affect the performance of only one Transact-SQL statement.
IF #a is null
Begin
-- code here
End
Read more about the syntax here

have you tried using the construct:
if (a)
begin
...
end
else if (b)
begin
...
end
else
begin
...
end
?

Related

Using IF statement with Variable value as Condition in SNowflake

I am new to snowflake and SQL scripting. I am trying to achieve a logic to execute commands in IF statement block when a variable condition is true using Snowflake, i went to the documentation but eventually i am doing mistakes in writing code. Can you please help me in correcting it.
//Step 1:
//Declare variable
declare
CNT NUMBER;
//Step 2:
//Assigning Value to variable
begin
CNT := (Select count(*) from CLOUDMED_AI.DATAWAREHOUSE_INTEGRATION_ADMIN.SYNAPSE_TO_SNOWFLAKE_CONTROL );
//Step 3:
//Using Variable in IF statement
IF (CNT < 100)
then
Select top 10 * from CLOUDMED_AI.DATAWAREHOUSE_INTEGRATION_ADMIN.SYNAPSE_TO_SNOWFLAKE_CONTROL
end IF;
end;
But the above lines for me is throwing issues.
Here is an example that works. Different table names, but you should be able to follow the structure.
execute immediate $$
declare
RECORD_COUNT NUMBER;
output RESULTSET;
begin
SELECT COUNT(*) INTO :RECORD_COUNT FROM INFORMATION_SCHEMA.TABLES;
IF (RECORD_COUNT<100) THEN
output:=(SELECT TOP 10 * FROM INFORMATION_SCHEMA.TABLES);
END IF;
RETURN TABLE(output);
end;
$$
;

Performance Issue due to GOTO statement

I'm using SQL Server 2016 database project and my script is like below
DECLARE Marker NVARCHAR(50) = (SELECT Value FROM Table1 WHERE name = 'Marker')
IF( IS NOT NULL)
BEGIN
IF #Marker = 'Marker1' GOTO Marker2;
IF #Marker = 'Marker2' GOTO Marker3;
IF #Marker = 'Marker3' GOTO Marker4;
IF #Marker = 'Marker4' GOTO Marker5;
IF #Marker = 'Marker5' GOTO Marker6;
IF #Marker = 'Marker6' GOTO Marker7;
ELSE GOTO EmptyBlock;
END
MARKER1:
Code for marker 1
MARKER2:
Code for marker 2
MARKER3:
Code for marker 3
.
.
.
EmptyBlock:
PRINT 'No changes'
This script file will be executed after every deployment and based on deployment it will be skipping the previous lines and now it will be reached to marker 15.
It's taking too much time to execute even though there are few lines of code, I've finally found the issue due to GOTO statements. I don't know if using GOTO is best practice or not, if its not good practice using it in production site then please give me the suggestions for an alternate of GOTO.
You can replace the GOTO statements with a script like this using IF:
-- get the number of the marker (instead of the full name of the marker).
DECLARE #Marker INT = (SELECT REPLACE(Value, 'Marker', '') FROM Table1 WHERE name = 'Marker')
IF #Marker IS NULL
BEGIN
PRINT 'no marker'
END
IF #Marker < 1
BEGIN
-- Code for Marker No. 1
END
IF #Marker < 2
BEGIN
-- Code for Marker No. 2
END
IF #Marker < 3
BEGIN
-- Code for Marker No. 3
END
IF #Marker < 4
BEGIN
-- Code for Marker No. 4
END
ELSE IF #Marker IS NOT NULL
BEGIN
PRINT 'no changes'
END
demo on dbfiddle.uk

Netezza while loop syntax

I want to make a statement in netezza so that it waits until a statement is correct before proceeding. Any help would be appreciated - something similar to the below
WHILE (
select count(*) EVENT_DESCRIPTION from TEST_DA_CONTROL.CTRL.C_DBA_MAINTENANCE_AUDIT
where EVENT_DESCRIPTION = 'STARTED' and DATETIME_LOGGED > (select add_months(current_date,0))) = 0
LOOP
wait 5
end loop;
but I don't know the correct syntax.
Best to assign that output to a variable. I seem to recall that getting data out of an execute immediate is a little arduous in nzplsql, but there are convenient variables already available for you to use. Here I'll use ROW_COUNT.
declare
event_descriptions int;
sql varchar;
begin
event_descriptions := 1;
while event_descriptions > 0 loop
--Actual work
sql := '
select * EVENT_DESCRIPTION from TEST_DA_CONTROL.CTRL.C_DBA_MAINTENANCE_AUDIT
where EVENT_DESCRIPTION = ''STARTED'' and DATETIME_LOGGED > (select add_months(current_date,0))) = 0;';
execute immediate sql;
event_descriptions := ROW_COUNT;
end loop;
end;

PLSQL: IF EXISTS in stored procedure while using loop

I am new to PLSQL. I am trying to create a procedure which iterates through an array.
My requirement is if one of the value is not found in table, it should add into FAILARRAY, otherwise it should add into PASSARRAY.
I was getting no data found exception even if it is handled, it goes out of the loop and next value in the loop is not getting iterated again.
Is there any way we can use if exists command here. Please help.
CREATE OR REPLACE PROCEDURE SCHEMA.PR_VALIDATE
(
FILEARRAY IN STRARRAY,
PASSARRAY OUT STRARRAY,
FAILARRAY OUT STRARRAY,
)
IS
--DECLARE
fileName VARCHAR2 (50);
fileId NUMBER;
BEGIN
for i in 1 .. FILEARRAY.count
loop
fileName := FILEARRAY(i);
DBMS_OUTPUT.put_line (FILEARRAY (i));
SELECT FILEID into fileId FROM TABLE_NAME WHERE FILENAME=fileName;
end loop
END;
I suspect you haven't realised that you can have a PL/SQL BEGIN ... END block, including an exception handler, within a loop. In fact, anywhere you can have PL/SQL statements you can have a block.
You mention an exception handler, although your code doesn't contain one. As you say your code goes 'out of the loop', I can only assume it's, well, outside of the for loop. But you can easily add a block, with an exception handler, inside the for loop, for example:
BEGIN
for i in 1 .. FILEARRAY.count
loop
fileName := FILEARRAY(i);
DBMS_OUTPUT.put_line (FILEARRAY (i));
-- Inner block starts at the line below:
BEGIN
SELECT FILEID into fileId FROM TABLE_NAME WHERE FILENAME=fileName;
-- TODO add to PASSARRAY
EXCEPTION
WHEN NO_DATA_FOUND THEN
-- TODO add to FAILARRAY
END;
end loop
END;
This way, if there are 8 values in FILEARRAY and no data is found in the table for the third value, the NO_DATA_FOUND exception gets caught without exiting the loop and the loop then progresses to the fourth value in FILEARRAY.
You are handling the exception but you need to avoid the exception. Try:
SELECT NVL(FILEID, "<Put Something here or leave it empty") FROM TABLE_NAME WHERE FILENAME=fileName;
That way if it finds a null value in the select it will just pull "" instead. Then you can check to see if your SELECT returns "" and if so populate your FAILARRAY, otherwise populate PASSARRAY.
CREATE OR REPLACE PROCEDURE SCHEMA.PR_VALIDATE(
FILEARRAY IN STRARRAY,
PASSARRAY OUT STRARRAY,
FAILARRAY OUT STRARRAY )
IS
fileName VARCHAR2 (50);
l_n_count NUMBER;
l_n_file_id NUMBER;
BEGIN
FOR i IN 1 .. FILEARRAY.count
LOOP
fileName := FILEARRAY(i);
DBMS_OUTPUT.put_line (FILEARRAY(i));
SELECT COUNT(FILEID) INTO l_n_count FROM TABLE_NAME WHERE FILENAME=fileName;
IF l_n_count =0 THEN
failarray(i):='No Value Found';
elsif l_n_count=1 THEN
SELECT FILEID INTO l_n_file_id FROM TABLE_NAME WHERE FILENAME=fileName;
Passarray(i):=l_n_file_id;
END IF;
END LOOP;
END;
/

Does T-SQL allow multiple ELSE IF? Or must I nest conditionals? SQL Server 2012

In C#, you can have multiple conditionals of which only one will execute:
if (Condition1)
{
// Condition1 is true.
}
else if (Condition2)
{
// Condition1 is false and Condition2 is true.
}
else if (Condition3)
{
// Condition1 is false and Condition2 is false and Condition3 is true.
}
else
{
// Condition1, Condition2, and Condition3 are false.
}
But does the same logic work in T-SQL or must you nest the statements? Will this execute exactly like the above code?
IF #variable1 = 1
BEGIN
--#variable1 = 1
END
ELSE IF #variable1 = 2
BEGIN
--#variable1 = 2
END
ELSE IF #variable3 = 3
BEGIN
--#variable1 = 3
END
ELSE
BEGIN
--#variable1 > 3
END
I might be wrong here, but isn't there a way the SQL code would not evaluate the same way as the C# code from a logic standpoint if SQL doesn't allow multiple conditionals like C#? For example, is execution of each new ELSE IF guaranteed to be exclusive of the previous statements?
Yes, they are the same. Only one condition will be executed and the order of conditions is crucial.
LiveDemo
DECLARE #variable1 INT = 2
,#variable3 INT = 3;
IF #variable1 = 1
BEGIN
SELECT 'First IF'
END
ELSE IF #variable1 = 2
BEGIN
SELECT 'Second IF'
END
ELSE IF #variable3 = 3
BEGIN
SELECT 'Third IF'
END
ELSE
BEGIN
SELECT 'Else Clause'
END
In both the C# case as well as the SQL Server case, the ELSE keyword indicates that ONLY one block beneath an IF statement with a valid condition is going to be executed. Without ELSE, that's when the behavior changes. Your example is fine.

Resources