ELSE SELECT nothing/blank - sql

I need to have an 'ELSE' statement for every conditional statement in my stored procedures, how do I return make a procedure return nothing?
IF EXISTS(SELECT 1 FROM Account WHERE Account.username=#Username)
BEGIN
SELECT Status
FROM Account
WHERE Account.username=#Username
END
ELSE
BEGIN
SELECT --nothing/blank
END
Thanks!

You can assign a variable:
IF EXISTS(SELECT 1 FROM Account WHERE Account.username=#Username)
BEGIN
SELECT Status
FROM Account
WHERE Account.username = #Username;
END;
ELSE
BEGIN
DECLARE #X int;
SELECT #X = 0;
END;

Something like this:
IF EXISTS(SELECT 1 FROM Account WHERE Account.username=#Username)
BEGIN
SELECT Status
FROM Account
WHERE Account.username=#Username
END
ELSE
BEGIN
SELECT "No rows found" as Status
END

IF EXISTS(SELECT 1 FROM Account WHERE Account.username=#Username)
BEGIN
SELECT Status
FROM Account
WHERE Account.username=#Username
END
ELSE
BEGIN
SELECT NULL--nothing/blank
END

Try this query
IF EXISTS(SELECT 1 FROM Account WHERE Account.username=#Username)
BEGIN
SELECT Status
FROM Account
WHERE Account.username=#Username
END
ELSE
BEGIN
SELECT NULL as 'Status'--nothing/blank
END

If you want to retrieve the Status value or NULL if there is no matching row you can use a subquery:
select ( select Status from Account where username = #Username ) as Status;
The outer select will always return a result. If the subquery doesn't supply a value then the result will be NULL.
If you want different, i.e. non-NULL, default value you can use Coalesce and a subquery thusly:
select Coalesce(
( select Status from Account where username = #Username ), -- If found.
0 -- Default value if not found.
) as Status;
NB: It is assumed that there is either a single matching row or no matching row. The code will fail if the subquery returns more than one value.
Note that by querying the table only once either solution avoids the possibility of a race condition with another session updating or deleting the row for a user between the exists check and the select that returns the Status value.

if you want to return nothing then no need to write else part.
It will shorten your code and easy to understand.
IF EXISTS(SELECT 1 FROM Account WHERE Account.username=#Username)
BEGIN
SELECT Status
FROM Account
WHERE Account.username=#Username
END
Else part is required when you want to return something else above condition failed.

Related

How can I generate a sequence number in a empty table

I am trying to make a query that can generate the latest sequence number +1 to the new record in sql server.
let ignore the insert part first, I write a query like this:
SELECT 'asdf' AS col1, CASE WHEN EXISTS (SELECT pk_sales_inv_no FROM salesInvoice WHERE pk_sales_inv_no LIKE 'Q-ARF2206-%') THEN 1 ELSE 0 END AS EXPR1
It looks fine, when the record with same prefix exists, It return 1, else 0.
Because I have to process the current latest sequence number in the true value part, so I change my query with this to get the pk_sales_inv_no for the true part processing.
SELECT TOP (1) 'asdf' AS col1, CASE WHEN EXISTS (SELECT pk_sales_inv_no FROM salesInvoice WHERE pk_sales_inv_no LIKE 'Q-ARF2206-%') THEN 1 ELSE 0 END AS EXPR1 FROM salesInvoice WHERE (pk_sales_inv_no LIKE 'Q-ARF2206-%') ORDER BY pk_sales_inv_no DESC
Then problem happens, because the select result is totally empty, so It doesn't return the 1 or 0.
How can I improve it to work out with a empty select result.
You can write a simple scalar udf, if you need it in JOIN adapt it as a table value function.
I doubt that this is what you need, I think you want to get the number after the 2nd dash
IF OBJECT_ID (N'dbo.udf_lastSequence') IS NOT NULL
DROP FUNCTION dbo.udf_lastSequence
GO
CREATE FUNCTION dbo.udf_lastSequence (#invNo varchar(100))
RETURNS int
AS
BEGIN
DECLARE #lastInvNo VARCHAR(100)
DECLARE #search VARCHAR(100)
DECLARE #result int
SET #result = 0
SET #search = CONCAT(#invNo, '%');
SELECT TOP 1 #lastInvNo = pk_sales_inv_no
FROM salesInvoice
WHERE (pk_sales_inv_no LIKE #search)
ORDER BY pk_sales_inv_no DESC
IF #lastInvNo IS NOT NULL
SET #result = CAST(REPLACE(#lastInvNo, #invNo, '') AS INT);
return #result
END
GO
Try it with SELECT dbo.udf_lastSequence('Q-ARF2206-') WITHOUT the final % charter

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

Stored Procedure to check the existence of email in tables

I am new to SQL stored procedures. I need to write a SQL to check a email exists in multiple tables. If a email contains in First Table it returns true and should not execute the rest. Like wise if not I need to check the second table and if i found return true. Finally if i found in last Table I need to return true and else i need to return false.
I am stuck in achieving this. I tried like this. Gives me syntax errors. Please share me a solution for this.
USE Users_UserDetials;
GO
CREATE PROCEDURE Users.GetUserPermissions
#userEmail nvarchar(50),
#areaId nvarchar(10),
#villageCode nvarchar(10)
AS
SET NOCOUNT ON;
IF EXISTS (SELECT 1 FROM Users.GlobalUsers AS GU
WHERE GU.UserEmail = #userEmail)
ELSE
IF EXISTS (SELECT 1 FROM Users.AreaSpecificUsers AS AU
WHERE AU.UserEmail = #userEmail)
ELSE
IF EXISTS (SELECT 1 FROM Users.VillageSpecificUsers AS VU
WHERE VU.UserEmail = #userEmail)
ELSE
'0'
GO
USE Users_UserDetials;
GO
CREATE PROCEDURE Users.GetUserPermissions
#userEmail nvarchar(50),
#areaId nvarchar(10),
#villageCode nvarchar(10)
AS
SET NOCOUNT ON;
IF EXISTS (SELECT 1 FROM Users.GlobalUsers AS GU
WHERE GU.UserEmail = #userEmail)
BEGIN
SELECT 1
END
ELSE
IF EXISTS (SELECT 1 FROM Users.AreaSpecificUsers AS AU
WHERE AU.UserEmail = #userEmail)
BEGIN
SELECT 1
END
ELSE
IF EXISTS (SELECT 1 FROM Users.VillageSpecificUsers AS VU
WHERE VU.UserEmail = #userEmail)
BEGIN
SELECT 1
END
ELSE
BEGIN
SELECT 0
END
END

SQL IF AND ELSE STATEMENT

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

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.