SQL Where clause based on Status - sql

Declare #Status nvarchar(25) = Null
Select * From Products
Where Type = 1
And
If Status is null, Don't add clause(means return all)
If Status = 'C', Add Status = 'Completed'
If Status = 'U', Add Status = 'Uncompleted'
How can I do this?

Don't call your variable the same as your column
Declare #MyStatus nvarchar(25) = Null
Select * From Products
Where Type = 1
AND (
(MyStatus is null)
OR (MyStatus = 'C' AND Status = 'Completed')
OR (MyStatus = 'U' AND Status = 'Uncompleted')
)

It would be better to simply assign the desired value to your #Status variable then you can simply check for equality -
where Type = 1 and (#status = status or #Status is null);

Related

Where clause filter in stored procedure

I'm trying to create a procedure where it needs to filter the records with where condition by multiple scalar parameters. I'm facing the problem with the column I.[status].
In that column the values will be as "pending", "rejected", "submitted". But when the value comes with "All", I need to select all the status types (pending, rejected, submitted)
CREATE PROCEDURE [dbo].[sp_cc_get_Invoices]
(#po_id INT = NULL,
#sortBy VARCHAR(50) = NULL,
#sortDirection VARCHAR(50) = 0,
#pageSize INT = NULL,
#page INT = NULL,
#TotalRows INT = NULL OUTPUT,
#time_zone_offset INT = 0,
#vendor_id VARCHAR(MAX) = NULL,
#status VARCHAR(20) = 'All',
#invoice_id INT = NULL,
#invoice_from_dt DATETIME2 = NULL,
#invoice_to_dt DATETIME2 = NULL)
AS
BEGIN
SELECT
I.invoice_id, I.invoice_amount, I.[status],
v.vendor_id, I.po_id, v.vendor_name,
I.netsuit_invoice_id, cd.currency_symbol
FROM
invoice_details I
LEFT JOIN
vendor_details v ON v.vendor_id = I.vendor_id
LEFT JOIN
currency_details cd ON cd.currency_id = I.currency_id
WHERE
(#po_id IS NULL OR I.po_id = #po_id)
AND (#vendor_id IS NULL OR I.vendor_id = #vendor_id)
AND (#invoice_id IS NULL OR #invoice_id = '' OR I.invoice_id = #invoice_id)
AND (I.invoice_date BETWEEN #invoice_from_dt AND #invoice_to_dt)
AND I.[status] = #status
END
How to filter all the status records?
You can express this with boolean logic.
Just change:
and I.[status] = #status
To:
and (#status = 'All' or I.[status] = #status)

Use if condition in where clause of sql query

I have a query that is:
SELECT DISTINCT DepotIo.Depot2Guid AS Depot1Guid, Depot2.Title, NULL AS Depot2Guid
FROM DepotIo
JOIN DepotIoDetail ON DepotIo.Guid = DepotIoDetail.DepotIoGuid
JOIN dbo.GetUserDepot(#UserGuid) AS Depot2 ON DepotIo.Depot2Guid = Depot2.Guid
JOIN Item ON Item.Guid = DepotIoDetail.ItemGuid
WHERE DepotIo.Company = #Company AND (DepotIo.Branch = #Branch)
But I want to when #Branch is not null, comes to WHERE condintion part and when it's value is null, relinquish it.. Like this :
WHERE DepotIo.Company = #Company AND (CASE #Branch
WHEN IS NOT NULL THEN DepotIo.Branch = #Branch)
what's true command ??
This is usually handled using or:
WHERE DepotIo.Company = #Company AND
(DepotIo.Branch = #Branch OR #Branch IS NULL)
You can use CASE WHEN as follows:
(CASE WHEN #Branch IS NOT NULL
THEN CASE WHEN DepotIo.Branch = #Branch THEN 1 ELSE 0 END
ELSE 1 END = 1)
Cheers!!
If I understand the question, this should do it.
If DeDepotIo.Branch is not nullable. This will relinquish rows where #Branch<>DeDepotIo.Branch, but not when #Branch is NULL.
WHERE DepotIo.Company = #Company AND (ISNULL(#Branch, DeDepotIo.Branch) = DeDepotIo.Branch)

Apply IF conditional at the end of the query

I'm new in sql server and I have WHERE clause like this:
WHERE[D].[IsLocked] = 0
AND(#StartDate IS NULL OR ISNULL([TA].[ModifiedDate], [TA].[CreationDate]) >= #StartDate)
AND(#EndDate IS NULL OR ISNULL([TA].[ModifiedDate], [TA].[CreationDate]) <= #EndDate)
AND((CASE WHEN[T].[TaskStatusId] = '09E02513-00AD-49E3-B442-A9ED2833FB25'
THEN 1 ELSE 0 END) = #Completed)
AND((#FilterEmpKey IS NULL AND[TA].[EmpKey] = #CurrentEmpKey)
OR (ISNULL([TA].[ModifiedAssignedBy], [TA].[AssignatedBy]) = #FilterEmpKey
AND[TA].[EmpKey] = #CurrentEmpKey))
But now I want to add if conditional in order to add more filters at the end of query like:
IF(#FilterEmpGuid IS NOT NULL)
AND[TA].[EmpKey] = #CurrentEmpKey
AND[TA].[AssignatedBy] = #CurrentEmpKey
AND[TA].[EmpKey] = #FilterEmpKey
But I get:
The multi-part identifier [TA].[EmpKey] could not be bound
What am I doing wrong?
IF conditionals are only for use outside sql queries, such as in procedures etc.
In a query itself you are limited to AND, OR and CASE statements, so you will need to rewrite your IF conditional for this:
AND (#FilterEmpGuid IS NULL
OR (
[TA].[EmpKey] = #CurrentEmpKey
AND[TA].[AssignatedBy] = #CurrentEmpKey
AND[TA].[EmpKey] = #FilterEmpKey
))
You could move the additional filter options into a scalar function.
If you know the additional fields that may be filtered, you may be able to get away with something like:
CREATE FUNCTION dbo.ExtendFilter(
#column_value VARCHAR(50), #param_value VARCHAR(50)
)
RETURNS BIT
AS
BEGIN
DECLARE #return BIT = 1; -- default RETURN to 1 ( include ).
IF ( NULLIF( #param_value, '' ) IS NOT NULL )
BEGIN
-- compare the column's value to the param value
IF ( #column_value <> #param_value )
SET #return = 0; -- don't include this record.
END
RETURN #return;
END
GO
And then use it like:
WHERE
{ other WHERE stuff }
AND dbo.ExtendFilter( [TA].[EmpKey], #CurrentEmpKey ) = 1
AND dbo.ExtendFilter( [TA].[AssignatedBy], #CurrentEmpKey ) = 1
AND dbo.ExtendFilter( [TA].[EmpKey], #FilterEmpKey ) = 1
Mind you this is just an example. You'd want to check #pram_value for NULL, etc...

Invalid column error in SQL Server 2008

I am trying to run the following query,
DECLARE #p_UserName as nvarchar(100)
DECLARE #p_Department as int
DECLARE #p_Section as int
DECLARE #p_SubSection as int
DECLARE #p_PermissionGroup as int
DECLARE #p_DistributionGroup as int
DECLARE #p_Permission as nvarchar(100)
DECLARE #p_IfPerChecked as bit
DECLARE #p_Role as int
SET #p_UserName = ''
SET #p_Department = NULL
SET #p_Section = NULL
SET #p_SubSection = NULL
SET #p_PermissionGroup = NULL
SET #p_DistributionGroup = NULL
SET #p_Permission = ''
SET #p_Role = NULL
SELECT Users.EnglishName,
(SELECT Designation.TitleEnglish FROM Designation WHERE Users.Designation = Designation.ID) AS [Role],
(SELECT Department.TitleEnglish FROM Department WHERE Users.DepartmentID = Department.ID) AS [Department],
(SELECT Section.TitleEnglish FROM Section WHERE Users.SectionID = Section.SectionID) AS [Section],
(SELECT SubSection.TitleEnglish FROM SubSection WHERE Users.SubSectionID = SubSection.SubSectionID) AS [Sub-Section],
(SELECT Groups.TitleEnglish FROM Groups WHERE
(SELECT UserRights.GroupID FROM UserRights WHERE Users.UserID = UserRights.UserID) = Groups.GroupID
AND Groups.IsDistribution = 0
) AS [Permissions Group],
(SELECT Groups.TitleEnglish FROM Groups WHERE
(SELECT UserRights.GroupID FROM UserRights WHERE Users.UserID = UserRights.UserID) = Groups.GroupID
AND Groups.IsDistribution = 1
) AS [Distribution Group],
(CASE
WHEN Users.ApplyUserRights = 1 THEN dbo.fn_GetUserPermissions('Users', Users.UserID)
WHEN Users.ApplyUserRights = 0 THEN dbo.fn_GetUserPermissions('Groups', (SELECT GroupID FROM UserRights WHERE Users.UserID = UserRights.UserID))
END) AS [Permissions]
FROM Users WHERE
((#p_UserName <> NULL OR #p_UserName <> '') AND #p_UserName = Users.UserName) OR
((#p_Department <> NULL OR #p_Department <> 0) AND #p_Department = Users.DepartmentID) OR
((#p_Section <> NULL OR #p_Section <> 0) AND #p_Section = Users.SectionID) OR
((#p_SubSection <> NULL OR #p_SubSection <> 0) AND #p_SubSection = Users.SubSectionID) OR
((#p_PermissionGroup <> NULL OR #p_PermissionGroup <> 0) AND #p_PermissionGroup = (
SELECT Groups.GroupID FROM Groups WHERE
(SELECT UserRights.GroupID FROM UserRights WHERE Users.UserID = UserRights.UserID) = Groups.GroupID
AND Groups.IsDistribution = 0
)) OR
((#p_DistributionGroup <> NULL OR #p_DistributionGroup <> 0) AND #p_DistributionGroup = (
SELECT Groups.GroupID FROM Groups WHERE
(SELECT UserRights.GroupID FROM UserRights WHERE Users.UserID = UserRights.UserID) = Groups.GroupID
AND Groups.IsDistribution = 1
)) OR
(1 = CASE
WHEN Users.ApplyUserRights = 1 AND #p_Permission = 'AllowChangePassword' THEN 0
ELSE dbo.fn_CheckPemission(#p_Permission, UserID)
END) OR
((#p_Role <> NULL OR #p_Role <> 0) AND #p_Role = Users.Designation) OR
(1 = 1)
GROUP BY CASE #GroupBy
WHEN 'DepartmentID' THEN Users.DepartmentID
WHEN 'SectionID' THEN Users.SectionID
WHEN 'SubSectionID' THEN Users.SubSectionID
ELSE Users.EnglishName
END
And I keep getting the error
Column 'Users.EnglishName' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.
Please help!
Like the message states, you need to group by the EnglishName column unless it is used in an aggregate function(Max or sum or likewise).
The issue is evident from your error message. Use GROUP BY in case of aggregate functions.

FireBird: How do you nest a select in an if?

I'm very new to FireBird, but I want to know how I can use a select statement as part of my conditional criteria. I feel like I've been to the internet in back trying to find a way to do this, but haven't come up with much. Below is my attempt at getting this to work. Thanks in advance for any help.
SET TERM ^ ;
ALTER PROCEDURE sp_test (
IPADD Varchar(32),
HN Varchar(32),
NOTE Varchar(200) )
RETURNS ( update_count integer )
AS
BEGIN
IF((SELECT COUNT(*)
FROM ADDRESSES a
WHERE a.ADDRESS_TYPE = 'Reserved'
AND a.ALIVE = 'N'
AND (a.HOST_NAME = '' OR a.HOST_NAME is NULL)
AND (a.DNS_NAME = '' OR a.DNS_NAME is NULL)
AND (a.SYSTEM_NAME = '' OR a.SYSTEM_NAME is NULL)) > 0)
THEN
UPDATE
ADDRESSES a
SET
a.HOST_NAME = :HN,
a.ADDRESS_TYPE = 'Assigned',
a.NOTES = :NOTE
WHERE
a.SHORT_IP_ADDRESS = :IPADD;
update_count = 1;
SUSPEND;
ELSE
update_count = 0;
SUSPEND;
END^
SET TERM ; ^
GRANT EXECUTE
ON PROCEDURE sp_test TO SYSDBA;
Using COUNT to check is there records to update is not the best way, use EXISTS instead, ie your IF would be
IF(EXISTS(SELECT 1 FROM ADDRESSES a
WHERE a.ADDRESS_TYPE = 'Reserved'
AND a.ALIVE = 'N'
AND (a.HOST_NAME = '' OR a.HOST_NAME is NULL)
AND (a.DNS_NAME = '' OR a.DNS_NAME is NULL)
AND (a.SYSTEM_NAME = '' OR a.SYSTEM_NAME is NULL)))
THEN
But there seems to be a problem with your return value, update_count - you return 1 if you execute the UPDATE, but the actual number of rows affected by the statement might be something else. I suggest you use ROW_COUNT context variable instead. So your procedure would be
ALTER PROCEDURE sp_test (
IPADD Varchar(32),
HN Varchar(32),
NOTE Varchar(200) )
RETURNS ( update_count integer )
AS
BEGIN
IF(EXISTS(SELECT 1 FROM ADDRESSES a
WHERE (a.ADDRESS_TYPE = 'Reserved')
AND (a.ALIVE = 'N')
AND (a.HOST_NAME = '' OR a.HOST_NAME is NULL)
AND (a.DNS_NAME = '' OR a.DNS_NAME is NULL)
AND (a.SYSTEM_NAME = '' OR a.SYSTEM_NAME is NULL)))
THEN BEGIN
UPDATE ADDRESSES a SET
a.HOST_NAME = :HN,
a.ADDRESS_TYPE = 'Assigned',
a.NOTES = :NOTE
WHERE a.SHORT_IP_ADDRESS = :IPADD;
update_count = ROW_COUNT;
END ELSE update_count = 0;
SUSPEND;
END^