SQL IF AND ELSE STATEMENT - sql

I have been trying to execute this if and else statement. However every execution indicates error such as either functional error or syntax related errors.
CREATE trigger [dbo].[TRIAL]
on [dbo].[TBL1]
after INSERT
AS
BEGIN
SET NOCOUNT ON;
IF TBL1.NUMBER = TBL2.NUMBER THEN
insert into TBL3 (NAME,HEIGHT)
select NAME,HEIGHT
from TBL1,TBL2
ELSE
PRINT 'WRONG NUMBER'
end
Would you please be able to help me to correct this?

To expand a bit on Alex K's comment:
declare #Flag bit = 1;
-- ERROR: There is no THEN keyword.
if #Flag = 1 then
select 'A';
-- CORRECT: Omit THEN and this works as expected.
if #Flag = 1
select 'A';
-- ERROR: Only the first SELECT is associated with the IF, so the ELSE is unmatched.
if #Flag = 2
select 'B1';
select 'B2';
else
select 'C';
-- CORRECT: If each branch of the IF has only one statement, then this construction is okay.
if #Flag = 2
select 'B1';
else
select 'C';
-- CORRECT: If you want multiple statements in either branch of the IF, make them into a block using BEGIN/END.
if #Flag = 2
begin
select 'B1';
select 'B2';
end
else
select 'C';
-- CORRECT: You can also use BEGIN/END with single statements if you like.
if #Flag = 2
begin
select 'B1';
select 'B2';
end
else
begin
select 'C';
end

Related

Multiple conditions without using multiple if else in SQL

I have to write a program in SQL that has multiple conditions but I shouldn't write it with multiple if else (because of the cost that if has). I'm new in this field and I have no idea how else could I write it which would be better
here is my sample code:
IF EXISTS(SELECT * FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_SCHEMA= 'dbo' AND TABLE_NAME = 'Food_tbl')
BEGIN
IF NOT EXISTS (SELECT TOP 1 FID FROM dbo.Food_tbl)
BEGIN
INSERT INTO dbo.Food_tbl
SELECT *
FROM DataFoodView
END
ELSE IF (SELECT COUNT(*) FROM dbo.Food_tbl)=20
BEGIN
PRINT N'Table Exists'
SELECT *
FROM Food_tbl
END
ELSE IF (SELECT COUNT(*) FROM dbo.FoodSara_tbl)<>20
BEGIN
print N'there isnt 20'
INSERT INTO Food_tbl (Food_tbl.FID, Food_tbl.Fname, Food_tbl.Ftype, Food_tbl.Fcount, Food_tbl.Datetype, Food_tbl.Fdescription)
SELECT DataFoodView.*
FROM DataFoodView
LEFT JOIN FoodSara_tbl ON Food_tbl.FID = DataFoodView.FID
WHERE Food_tbl.FID IS NULL;
END
END
PS: I have at first check if the table is exits and if it hasn't any record insert all the data, if it has 20 records show the table, if the table doesn't have 20 records find the missing data then insert that.
First, the condition in the ELSE part isn't needed :
change
ELSE IF (SELECT COUNT(*) FROM dbo.FoodSara_tbl)<>20
BEGIN
to
ELSE
BEGIN
Next, you may regroup the two INSERT parts because having no element is also having else than 20 elements.
The result will be something like that :
IF EXISTS
(
SELECT * FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_SCHEMA= 'dbo' AND TABLE_NAME = 'Food_tbl'
)
BEGIN
IF (SELECT COUNT(*) FROM dbo.Food_tbl)=20
BEGIN
PRINT N'Table Exists'
SELECT *
FROM Food_tbl
END
ELSE
BEGIN
print N'there isnt 20'
INSERT INTO Food_tbl (Food_tbl.FID, Food_tbl.Fname, Food_tbl.Ftype,
Food_tbl.Fcount, Food_tbl.Datetype, Food_tbl.Fdescription)
SELECT DataFoodView.*
FROM DataFoodView
LEFT JOIN FoodSara_tbl ON Food_tbl.FID = DataFoodView.FID
WHERE Food_tbl.FID IS NULL;
END
END
Not understood the exact requirement from the description what you have provided but just review the following logic
IF EXISTS(SELECT * FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_SCHEMA= 'dbo' AND TABLE_NAME = 'Food_tbl')
BEGIN
DECLARE #RCount INT
SELECT #RCount= COUNT(FID) FROM dbo.Food_tbl
IF #RCount=0
BEGIN
//Your Logic 1 (for inserting data since no records found)
END
ELSE
BEGIN
PRINT N'Table Exists'
IF #RCount=20
BEGIN
//Your Logic 2
END
ELSE
BEGIN
//Your Logic 3
END
END
END
Please explain the requirement in details or build your queries based on the requirement and add in place of Logic 1,2,3

why does this inline count() condition return an error?

The following t-sql works as expected:
--test1
DECLARE #IntValCount INT;
SELECT #IntValCount = COUNT(IntVal) FROM #AppIdList;
IF(#IntValCount = 0)
BEGIN
print 'test1'
END
However, if I try to write the count() condition as an inline expression with the following sql then ssms returns the error "Incorrect syntax near '='":
--test2
IF(SELECT COUNT(IntVal) FROM #AppIdList = 0)
BEGIN
print 'test2'
END
Am I writing the sql for test2 incorrectly or dos ss not allow this particular approach for some reason?
Your parens are in the wrong place:
IF ( (SELECT COUNT(IntVal) FROM #AppIdList) = 0)
BEGIN
print 'test2'
END;
However, it is better to use NOT EXISTS:
IF ( NOT EXISTS (SELECT 1 FROM #AppIdList WHERE IntVal IS NOT NULL) )
BEGIN
print 'test2'
END;
Why? NOT EXISTS can stop at the first matching value. SELECT COUNT() has to read all the potential values.

SQL IF/ELSE Statement

I'm struggling to understand why the below SQL will not work. I've put a comment (----------Fine up to Here), which is where SQL Server will accept the code when I parse/save the Store proceedure.
The bit below that, it will not take. Still new to SQL so any help would be great.
The error I receive is, Incorrect syntax near the keyword 'ELSE'. The "ELSE" being the one under the comment I mentioned above.
What I also don't understand is, If I change the IF and the BEGIN round, SQL accepts it (below)? I thought ELSE IF was not possible.
----------Fine up to Here
ELSE
IF (#GrabTypeID = '')
BEGIN
****************************************
Code below
**************************************
IF (#GrabtypeID NOT IN (SELECT GRABTYPEID FROM Mytable) AND #GrabtypeID != '') OR
(#Variable1 NOT IN (SELECT ID FROM Mytable) AND #Variable1 !='')
BEGIN
SELECT #ErrorMessage ='The GrabTypeID or the ID is an invalid value'
RAISERROR (#ErrorMessage, 16, 1)
PRINT 'Invalid Parameters passed Through'
RETURN
END
ELSE
BEGIN
IF (#GrabtypeID ! ='')
TRUNCATE TABLE Datatable1
TRUNCATE TABLE Datatable2
INSERT Datatable1
SELECT * FROM Referencetable1
INSERT Datatable2
SELECT * FROM REFERENCETABLE2
END
----------Fine up to Here
ELSE
BEGIN
IF (#GrabTypeID = '')
TRUNCATE TABLE Datatable1
TRUNCATE TABLE Datatable2
INSERT Datatable1
SELECT * FROM REFERENCETABLE1 WHERE CATEGORY = 4
INSERT Datatable2
SELECT * FROM REFERENCETABLE2 WHERE CATEGORY = 4
END
GO
Your format is a little weird. You could make it work the way you have it, but I think it would be better to use this format:
IF expression
BEGIN
SELECT
END
ELSE IF expression
BEGIN
SELECT
END
ELSE IF expression
BEGIN
SELECT
END
Specifically, change this:
ELSE
BEGIN
IF (#GrabtypeID ! ='')
To this (in both places):
ELSE IF (#GrabtypeID ! ='')
BEGIN

if condition not working

I want to show a message if record is not in the table.
I wrote this small piece of code, but it's giving me an error.
create procedure abc(#id varchar(25))
as
declare #msg1 as varchar(55)
begin
select id,fname,lname from student where id=#id
--up to this is working correctly
--for showing msg i write down this lince of code
if id=#id
select #msg=“correct record“
else
select #msg=“record not found“
end
end
Add an EXISTS check instead of selecting the records
IF EXISTS ( select 1 from student where id=#id)
BEGIN
SET #msg = 'correct record'
END
ELSE
BEGIN
SET #msg = 'incorrect record'
END
Are you trying to return the value of #msg? If yes, add SELECT #msg at the end.
Use single quotes not double. And check for any results with ##rowcount
create procedure abc(#id varchar(25))
as
begin
select id,fname,lname from student where id=#id
if ##rowcount > 0
select 'correct record' as msg
else
select 'record not found' as msg
end
end

SQL Replace an empty SQL SELECT with word else post the result in Oracle

I'm trying to solve the following problem:
I would like to make a select, when the result is empty it should be replaced with 'empty' Else all lines of the result should be there.
Like:
if (select has no result)
{
One Line as result with 'no result'
}
else
{
post every line of the select result
}
That is my try:
select case when count(*) = 0
then 'no Entry'
else Members --all Members should be here
END as Member
from tableMember where Membergroup = 'testgroup';
Thanks to everybody who can help me!
PLEASE show me the COMPLETE code that is needed to use the query in Oracle
Try this:
DECLARE #counter int
SET #counter = (select count(*) from tableMember where Membergroup = 'testgroup');
IF (#counter > 0)
BEGIN
SELECT * FROM Members
END
ELSE
BEGIN
SELECT 'No results!'
END
Regards
FOR ORACLE
DECLARE C INTEGER;
SELECT COUNT(*) INTO C FROM tableMember WHERE Membergroup = 'testgroup';
IF C > 0
THEN
SELECT * FROM tableMember;
ELSE
SELECT 'No results!' FROM tableMember;
END IF;
MS-SQL ONLY
IF EXISTS(SELECT * FROM tableMember WHERE Membergroup = 'testgroup')
BEGIN
SELECT * FROM tableMember
END
ELSE
BEGIN
SELECT 'No results!'
END
I would rather do this in the application code rather than stored procedures. What you are trying to do here is user experience related work which IMHO is something database should not care about.