How to handle True, False or NULL in where clause - sql

How can I reduce this to only one where statement
#state as bit
IF #state IS NULL
SELECT * FROM TBL WHERE name IS NULL
ELSE
SELECT * FROM TBL WHERE name = #state
I wish I could compare True, False or NULL in one select statement

Would this not work?
SELECT *
FROM TBL
WHERE (#state is null and name is null) or
(name = #state)
Another approach would be to use coalesce on both conditions.

If using MySQL, here is a simpler way:
SELECT * FROM TBL WHERE name <=> #state;

Related

SQL WHERE With Nullable Parameter

I have a SQL Query that I need to return rows based on the following possibilities:
ReqType
------
NULL
LTL
TL
To get a better idea of what I want to achieve:
SELECT * FROM MyTable MT
WHERE MT.ReqType = #param1
The parameter that is being passed is #param. Possibilities for #param can be NULL, TL or LTL.
#param and ReqType are nvarchar(3)
NULL doesn't work with =, so you need more explicit logic:
WHERE (MT.ReqType = #param1 OR
(MT.ReqType IS NULL AND #param1 IS NULL)
)
If #param1 (can be) SQL NULL then you could also do:
SELECT * FROM MyTable MT
WHERE isnull(MT.ReqType, '') = isnull(#param1,'')
*That would not work if you are allowing empty string for your MT.ReqType. In that case you could pick another char to replace null values with.
Works the same as Gordon's, a little more compact, note the use of coalesce. I don't think this is Index friendly so you might want to be careful how you use it.
declare #test table
(
ReqFld1 varchar(4),
ReqType varchar(3)
)
insert into #test values ('FLD1', 'LTL')
insert into #test values ('FLD2', 'TL')
insert into #test values ('FLD3', NULL)
declare #srch varchar(3)
select #srch = null
select * from #test
where coalesce(ReqType, '') = (coalesce(#srch, ''))
select #srch = 'LTL'
select * from #test
where coalesce(ReqType, '') = (coalesce(#srch, ''))
select #srch = 'TL'
select * from #test
where coalesce(ReqType, '') = (coalesce(#srch, ''))

Write into temp table from two alternate sql statements

I want to write the output of two queries into a table based on a condition. I have this piece of query but does not work. Please advise.
DECLARE #promptflag varchar(1) = 'N';
DECLARE #pool varchar(10) = 'PJMRTO';
IF Object_id('tempdb..#pnode') IS NOT NULL
DROP TABLE #pnode;
select
case when #promptflag='Y' then
(select distinct YES_PNODE from PRICE_NODES where ISO = #pool and Biddable='Y')
when #promptflag='N' then
(select distinct YES_PNODE from PRICE_NODES where ISO = #pool and Biddable='Y' and NonPrompt_Node='Y')
end
INTO #pnode
The idea is more like this:
select distinct YES_PNODE
into #pnode
from PRICE_NODES
where ISO = #pool and Biddable = 'Y' and
(#promptflag = 'Y' or NonPrompt_Node = 'Y');
The or expression is just a shortening of your query logic.

Return Value Column Name

The stored procedure below works correctly as expected. Returning True if "FleetBarcode" exists and False if it doesn't.
However, when it returns it it displays it as below
(no column name)
True
My problem is I need the "No Column Name" part to have a defined column name. Tried the method below so far which gives the 'True' field an alias.
Thank you for your time.
ALTER proc [dbo].[usp_getjobs]
#barcode as nvarchar(20)
as
SELECT CASE WHEN EXISTS(
SELECT
[FleetBarcode],
[Deleted]
FROM w_DeliveryItems
WHERE FleetBarcode = #barcode
AND Deleted != 1
)
THEN (SELECT 'True' 'Exist')
ELSE (SELECT 'False' 'Exist')
END
Use
ALTER PROC [dbo].[usp_getjobs] #barcode AS NVARCHAR(20)
AS
SELECT CASE
WHEN EXISTS(SELECT [FleetBarcode],
[Deleted]
FROM w_DeliveryItems
WHERE FleetBarcode = #barcode
AND Deleted != 1) THEN 'True'
ELSE 'False'
END AS [Exist]
The alias needs to go on the outer SELECT.
Also for column aliasing it is more common to use square brackets than single quotes.
Get rid if the SELECTs in the THEN/ELSE blocks and use AS to give the column a name:
SELECT CASE WHEN EXISTS(
...
THEN 'True')
ELSE 'False')
END AS [Exist] --<-- add name here
ALTER proc [dbo].[usp_getjobs]
#barcode as nvarchar(20)
as
SELECT CASE WHEN EXISTS(
SELECT
[FleetBarcode],
[Deleted]
FROM w_DeliveryItems
WHERE FleetBarcode = #barcode
AND Deleted != 1
)
THEN (SELECT 'True' 'Exist')
ELSE (SELECT 'False' 'Exist')
END AS [Your Column Name]

Null and not null values in the same parameter

I have this:
Decalre #param int
select * from table where param = #param
sometimes people would like to select records where param is null.
so, something like this:
if #param is null
begin
select * from table where param is null
end
else select * from table where param =#param
Is it possible to incorporate this in a single query?
Should be able to cover it off in a where clause:
select * from table where (param =#param) or (param is null and #param is null)
Would use the coalesce to replace the null value, will act better on performance than the or i think :
SELECT *
FROM table
WHERE Coalesce(#param, 1) = Coalesce(param, 1)
select
*
from table
where (#param is null AND param is null) OR (#param is not null AND param = #param)

Using Case Statement in SQL with parameter/variable to check for Null values

I am trying to write a SQL Select statement to return records based on a user input through a front end.
I want to write the Select statement like this:
SELECT somefields
FROM sometable
WHERE CASE variable
WHEN 'blank' THEN field IS NULL
ELSE field = field
END
Basically I either want to filter a column to find NULL values or ignore the filter and return all values depending on the value of the variable. I know that the results of the CASE statement is not executable but how can I do this?
When variable is 'blank', the following query will give you rows where field is NULL. When variable is anything else, it will give you all rows:
SELECT somefields
FROM sometable
WHERE
(variable = 'blank' AND field IS NULL)
OR (variable <> 'blank')
You can use NULLIF() (link is for SQL Server, but NULLIF() should be standard):
SELECT somefields
FROM sometable
WHERE field = NULLIF(variable, 'blank')
The following snippet should behave as follows:
when #variable is null, return all rows
when #variable = 'blank', return all rows where field is null or field = 'blank'
otherwise, return rows where #variable equals field
Code snippet:
WHERE 1 = CASE
WHEN #variable is null then 1
WHEN #variable = 'blank' and field is null then 1
WHEN #variable = field then 1
END
SELECT somefields
FROM sometable
WHERE ((variable IS NULL OR variable = 0) OR (variable = field))
WHERE Criteria is apply when variable have value
For Example:
DECLARE #CityName VARCHAR(50)
SET #CityName = NULL
SELECT CityName
FROM City
WHERE ((#CityName IS NULL ) OR (#CityName = CityName ))
When City is null then tables return all rows
I think I get what you're after. Something like this maybe?
SELECT field1,
field2,
CASE variable
WHEN 'blank' THEN NULL
ELSE field3
END as field3
FROM sometable
Think I understand what you mean....for example....
SELECT
House, Postcode
from
SomeTable
where
(House=isnull(#House,House) or (House is null and #House is null))
and
(Postcode=isnull(#Postcode,Postcode) or (Postcode is null and #Postcode is null))
First bit of the conditional where is to use the variable, when present (the isnull bit is to ignore the variable if it's null)
Second bit of the conditional where is in case your evaluative field is null also as effectively fields don't = null they are 'is null'.
Confused? Good. Works on what I'm doing though!
Here is my solution based on #Andomar answer above aimed at anyone testing an input varchar value, you need to test the parameter in the right order as per the example below:
FIELD1 = CASE
WHEN #inputParameter = '' THEN FIELD1
WHEN #inputParameter <> FIELD1 THEN NULL -- if input is some text but does not match
WHEN #inputParameter IS NULL THEN FIELD1
WHEN #inputParameter != '' AND FIELD1 = #inputParameter THEN FIELD1
END
Hope this helps someone.