Selecting Columns Based on Case or If Statements - sql

I wan't to display columns based on conditions/parameters
what i want is
if(#SelectFlag==true)
select name,Address,salary,CreatedBy from employee
else (#UpdateFlag==true)
select name,Address,salary from employee
-- in this case i don't require the column "CreatedBy"
How can i make a query or stored procedure looking at the above circumstances..
Thanks & regards..

Use single = and 1 instead of true.
if #SelectFlag = 1
select name, Address, salary, CreatedBy from employee
else
if #UpdateFlag = 1
select name, Address, salary from employee

here's an example for creating stored procedure, maybe you need to have only one parameter that indicates what are you trying to do
CREATE PROCEDURE procedurenameHere(#EventFlag INTEGER)
AS
-- #EventFlag
-- 1 for SELECT
-- 2 for UPDATE
IF #EventFlag = 1
SELECT name,Address,salary,CreatedBy
FROM employee
ELSE IF #EventFlag = 2
SELECT name,Address,salary, NULL AS CreatedBy
FROM employee
GO
execution:
EXEC procedurenameHere 1

Try this
Table : emp
Columns : name, address, salary, creditedBy
declare My_Block
p_select_flag emp.SelectFlag%type;
p_updateFlag emp.UpdateFlag%type;
BEGIN
select selectFlag into p_select_flag from emp where name='ASIF';
select update into p_updateFlag from emp where name='ASIF';
IF p_select_flag = 'TRUE' THEN
select name,Address,salary,CreatedBy from employee;
ELSIF UpdateFlag = 'TRUE' then
select name,Address,salary from employee;
END IF;
END My_Block

U can call inside the SP with parameter and pass one parameter as FLAG as Integer:
Use single = and 1,2 instead of true.
1 INDICATE FOR SELECT AND 2 INDICATE FOR UPDATE
if #FLAG = 1
select name, Address, salary, CreatedBy from employee
else
if #FLAG = 2
select name, Address, salary from employee

Related

SQL comparing each row to a reference row

I am trying to compare each row from a select statement to a reference row.
So to put it into context I would like to find the reference row which is the account details for one of our users.
SELECT id, first_name
FROM account
WHERE id = '100'
Would return the info for the user in question
Then I want to run a SELECT statement to return all users - pretty straightforward
SELECT id,first_name
FROM account
For each row I would like to compare the first_name with the reference row. If it is the same return a '1' if it is different return a '0'
I can do this if I type in the value to compare e.g 'Paul'
SELECT id,first_name,
CASE
WHEN first_name = 'Paul' THEN '1'
ELSE '0'
END
FROM account
But obviously I want to replace Paul with whatever the first_name is from the reference row above.
My googling suggests I need to declare a variable and then something with SELECT INTO a variable
DO $$;
Declare
#reference_first_name text;
BEGIN
SELECT first_name
into #reference_first_name
FROM account
WHERE id = ‘100’
END;
But I can't seem to put it together.
Then to go a step further would it be possible to reference multiple columns?
You could do this simply in a subquery:
demo:db<>fiddle
SELECT
id,
first_name,
CASE
WHEN (SELECT first_name FROM users WHERE id = 100) = first_name THEN 1
ELSE 0
END
FROM users;
Other ways are using a CTE or a JOIN (see fiddle for these versions)
Here's another option using an outer join:
select a.id, a.first_name, case when a.first_name = b.first_name then 1 else 0 end
from account a
left join account b on b.id = 100
Online Demo
Use correlated subquery as :
select a.id, a.first_name,
( select count(*)
from personnel p
where p.id = 100
and upper(p.first_name) = upper(a.first_name) ) as flag
from account a;
provided you have a table called personnel and has an ID fixed for all comparisons.
Rextester Demo

SQL Return predefined string when row do not exists

select name, designation, salary
from employee
where employeeID = 123
If employeeID 123 doesn't exist sql should return "EmployeeID is not valid".
I tried Union and case statements but I am not getting the result needed.
Database : SQL Server
This actually has to be done at application level rather than SQL, but you can validate it using NOT EXISTS :
IF NOT EXISTS (SELECT 1 FROM employee WHERE employeeID = 123)
BEGIN
PRINT 'EmployeeID is not valid' --- OR USE RETURN
-- SELECT 'EmployeeID is not valid' --- OR SELECT statement with message
END
ELSE
BEGIN
SELECT name, designation, salary
FROM employee
WHERE employeeID = 123
END

Select an ID if count is equal to 1

I am trying to write a query which needs to find an ID number from 3 WHERE values based on the result only being equal to 1.
So say i want to find a patient's ID and my where clause matches the firstname, lastname and DOB. If there are 2 results because of duplicates, i need the output to be NIL else it should return the patient ID.
if(select count(*)
from patient
where last_name = 'JAMES'
and first_name = 'JONES'
and birth_DtTM = '1980-01-01') > 1
print 'NULL' else return Pat_ID1
This is kind of what i am leading towards.
Thanks guys
select case when count(*)> 1
then 'NULL' else Pat_ID1 end
from patient
where last_name = 'JAMES'
and first_name = 'JONES'
and birth_DtTM = '1980-01-01'
group by Pat_ID1
try below.
;WITH CTE(Pat_ID1,last_name,first_name,birth_DtTM,dup_rows)
as
(
SELECT Pat_ID1,last_name,first_name,birth_DtTM,ROW_NUMBER() OVER(PARTITION BY last_name,first_name,birth_DtTM ORDER BY Pat_ID1) AS dup_rows FROM patient
)
SELECT
case when dup_rows>1 then null
when dup_rows=1 then Pat_ID1
end
FROM CTE
You can do it like this:
SELECT
PatientID = CASE COUNT(*) WHEN 1 THEN MAX(Pat_ID1) END
FROM
patient
WHERE
last_name = 'JAMES'
AND first_name = 'JONES'
AND birth_DtTM = '1980-01-01'
;
The CASE expression will evaluate either to the single Pat_ID1 matching the request or to NULL (if COUNT(*) is anything but 1).
As you can see, the Pat_ID1 value is obtained with the help of an aggregate function (by the way, you can use MIN instead of MAX just as well). This is because the presence of COUNT(*) in the query automatically implies grouping and now, if you want to reference columns of the underlying row set, you must only access their aggregated values.

case statement in select query in sql

I have a stored procedure to load the data from one table to another table.
i need to set the column value of the destination table based on the two values of the select statement, some thing like the below example.
insert into table table_name
( value1, value 2,value 3)
select (value 1,value2 ,
case value3
when value1 = 'somevalue' &&* value2 = 'somevalue'
then 'x'
else 'y'
End
from table_name.
can any one help me to find out how to update the a column in based on the two previous column values in the same select query?
i have tried with the below sample example to understand but it was failed to parse.
INSERT INTO HumanResources.departmentcopy
( DepartmentID,GroupName,Name,temp)
SELECT DepartmentID,GroupName,Name,
CASE temp
WHEN DepartmentID = 1 && Name = 'Engineering and Research'
THEN 'sucessful'
ELSE 'unsucessful'
END
FROM HumanResources.department
Help me on this!!
thanks,
Venkat
You were very close:
INSERT INTO HumanResources.departmentcopy(DepartmentID, GroupName, Name, temp)
SELECT DepartmentID,
GroupName,
Name,
CASE WHEN DepartmentID = 1 AND Name = 'Engineering and Research'
THEN 'sucessful' ELSE 'unsucessful' END
FROM HumanResources.department
&& is not valid in SQL. Use AND to append a condition.
INSERT INTO HumanResources.departmentcopy( DepartmentID,GroupName,Name,temp)
SELECT DepartmentID,
GroupName,
Name,
CASE
WHEN DepartmentID = 1 AND Name = 'Engineering and Research' THEN 'sucessful'
ELSE 'unsucessful'
END
FROM HumanResources.department
INSERT INTO HumanResources.department(DepartmentID, GroupName, Name, temp)
SELECT DepartmentID,
GroupName,
Name,
CASE WHEN DepartmentID = 1 AND Name = 'Engineering and Research'
THEN 'sucessful' ELSE 'unsucessful' END
FROM HumanResources.department

Only one expression can be specified in the select list when the subquery is not introduced with EXISTS

I have a SQL query which selects some values (and works across tables in the form of a join). One of the fields returns 0 or 1 but I want to return something else in the case of 0, or the case of 1 (yes/no).
The code:
SELECT Passed,
CASE Passed
WHEN '1' THEN 'Yes'
ELSE 'No'
END
FROM EXAM_INSTANCE
Works perfectly well.
But when I integrate this as a sub-query in the stored proc, I get the error:
Only one expression can be specified in the select list when the sub-query is not introduced with EXISTS.
The original query is:
select Firstname, Lastname, ei.Started,
((ei.totalcorrect*100)/#examQuestionCount) as percentage, passed, ei.InstanceID
from ea ei, INVITE i, OSTTable ost, f f
where ei.Finished is not null
and ei.InviteID = i.InviteID
I am trying:
select Firstname, Lastname, ei.Started,
((ei.totalcorrect*100)/#examQuestionCount) as percentage,
(SELECT Passed,
CASE Passed
WHEN '1' THEN 'Yes'
ELSE 'No'
END
FROM EA),
ei.InstanceID
from EA E ei, INVITE i, osttable ost, ef e
where ei.Finished is not null
and ei.InviteID = i.InviteID
What is the cause for my error?
PS I've changed table names for privacy reasons so don't worry if they don't match up.
A subquery in that position is expected to return no more than one value (i.e. one column in one row), but your subquery returns two columns (one is Passed, the other is an unnamed column represented by the CASE expression) and I cannot know how many rows.
You should either integrate the results of the subquery into your main query (something along the lines of what #Alex_L is suggesting) or limit the subquery's output to the expected quantity of values.
select Firstname, Lastname, ei.Started,
((ei.totalcorrect*100)/#examQuestionCount) as percentage,
passed_ = CASE Passed
WHEN '1' THEN 'Yes'
ELSE 'No'
END,
ei.InstanceID
from EA E ei, INVITE i, osttable ost, ef e
where ei.Finished is not null
and ei.InviteID = i.InviteID
USE [IAS_AccountDB]
GO
/* Object: StoredProcedure [dbo].[Prc_Accounts_LastNodes] Script Date: 04/01/2013 01:29:20 */
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[Prc_Accounts_LastNodes]
(
#AccountParentID int = NULL
)
AS
SELECT
[Accounts].[AccountName]
,[Accounts].[AccountID]
FROM
[Accounts]
WHERE
#AccountParentID IN
(
SELECT
[Accounts].[AccountID]
,[Accounts].[AccountName]
,[Accounts].[AccountStandardCode]
FROM
[Accounts]
WHERE
NOT EXISTS
(
SELECT TOP 1
1
FROM
[Accounts_ParentIDs]
WHERE
[Accounts_ParentIDs].[AccountParentID] = [Accounts].[AccountID]
)
)
RETURN 0;