SQL check length of a list argument - sql

I have a following query in an Azure SQL database:
Select *
from item_table
where itemNumber IN (:itemNbr) or (:itemNbr) is null;
Means, if the passed list :itemNbr is null or empty then I want all the rows from the table.
The problem I am getting with this query is it runs fine if the :itemNbr is null or empty, but if I pass some objects in the list, then it becomes like this:
Select *
from item_table
where itemNumber IN ('2134234', '23423423') or ('2134234', '23423423') is null;
and I get this error while executing it:
SQL Error [4145] [S0001]: An expression of non-boolean type specified in a context where a condition is expected, near ','
I have tried ISNULL, NULLIF and some other ways but nothing is working correctly

Found one way to handle the same in the query itself, without changing the application code:
Select * from item_table where (COALESCE(:itemNbr,1) = 1 or itemNumber in ( :itemNbr ));
So Now, if we pass the arg itemNbr as null then it will fetch all the rows from the table or else it will filter the rows basis on the itemNbr argument.

Related

Can I know the issue of this SQL query

I have this SQL query:
but I'm getting an error:
If I remove the comma-separated value from the variable, it is working fine. As well as if I remove the NULL checking feature it is working fine. Can I know the issue of this
It's because a CASE WHEN can only return 1 value.
And a STRING_SPLIT returns a resultset.
I assume something like this is what you want.
SELECT *
FROM Facility f
WHERE (#Facility IS NULL OR f.facilityCode IN (SELECT value FROM string_split(#Facility,',')))
This will get all records if the variable is null.
The function dbo.split will split the string in more than one value. This will confuse your subquery and the error you are receiving will be thrown.
In case you need what goes before the comma consider using:
select top 1 value
from dbo.split(#Facility, ','))
You want to say if the variable is NULL so ignore the WHERE statement, if so your query would be:
SELECT *
FROM Facility f
WHERE #Facility IN (select value from dbo.split(#Facility, ',')) OR #Facility IS NULL

Filtering 'Where In' Queries by 'Is Not Null' in Big Query

I am attempting to query a table in BigQuery programmatically, and have a WHERE-IN clause that I would like to support having NULL as the value. Current Query looks like:
SELECT * FROM DATASET.TABLE_NAME WHERE HIT_DATE = 'YYYY-MM-DD' AND ID IN (LIST_OF_IDS);
I am wondering if there is a way so that I can query everything from the table for a specific date in the case that the LIST_OF_IDS input is NULL (The idea being that I want to support choosing between an inputting of a list of ids or return everything if no list of ids are given).
I tried
SELECT * FROM DATASET.TABLE_NAME WHERE HIT_DATE = 'YYYY-MM-DD' AND ID IN (LIST_OF_IDS) IS NOT NULL;
But got this error thrown at me:
Syntax error: Expression to the left of IS must be parenthesized
If I understand correctly you are looking for this :
SELECT *
FROM DATASET.TABLE_NAME
WHERE HIT_DATE = 'YYYY-MM-DD'
AND (ID IN (LIST_OF_IDS) OR LIST_OF_IDS IS NULL);

Snowflake case statement is returning an error instead of the value specified within the ELSE clause

I need to check if one or many fields already exists in a table so I can do a merge into statement using them.
I tried this:
select sat_sector_hkey,
CASE
WHEN EXISTS(select id from hub_sector)
THEN (MERGE INTO ...)
END AS id
from sat_sector;
For testing, I used only one case statement, and replaced merge into with a THEN...ELSE values:
SELECT sat_sector_hkey,
CASE
WHEN EXISTS(select id from hub_sector)
THEN '1'
ELSE ''
END AS id
FROM sat_sector;
When this field does not exists, the query return an error instead of '':
SQL compilation error: error line 3 at position 23 invalid identifier
'ID'
I am using a CASE, because I need to check if a column exists or not, as I don't know if it exists or not due to some technicalities in our data coming from multiple sources.
Try this:
Construct an object with the full row.
Test if the constructed object has data for "ID".
create or replace temp table maybe_id
as
select 1 x, 2 id;
select *,
case
when object_construct(a.*):ID is not null
then '1'
else ''
end as id
from maybe_id a
;
Works for me - it gives 1 when the column id has data, and `` when the column doesn't exist in the table.

sql server - how to execute the second half of 'or' clause only when first one fails

Suppose I have a table with following records
value text
company/about about Us
company company
company/contactus company contact
I have a very simple query in sql server as below. I am having problem with the 'or' condition. In below query, I am trying to find text for value 'company/about'. If it is not found, then only I want to run the other side of 'or'. The below query returns two records as below
value text
company/about about Us
company company
Query
select
*
from
tbl
where
value='company/about' or
value=substring('company/about',0,charindex('/','company/about'))
How can I modify the query so the result set looks like
value text
company/about about Us
A bit roundabout, but you can check for the existence of results from the first where clause:
select
*
from
tbl
where
value='company/about' or
(
not exists (select * from tbl where value='company/about')
and
value=substring('company/about',0,charindex('/','company/about'))
)
Since your second condition can be re-written as value = 'company' this would work (at least for the data and query you've presented):
select top(1) [value], [text]
from dbo.MyTable
where value in ('company/about', 'company')
order by len(value) desc
The TOP() ignores the second row if both are found, and the ORDER BY ensures that the first row is always the one with 'company/about', if it exists.

Issue with 'NOT IN' statement in SQL

Can anyone please point out what is wrong with the following SQL statement:
SELECT DiaryType
FROM tblDiaryTypes
WHERE DiaryType NOT IN (SELECT NextDiary
FROM tblActionLinks
WHERE HistoryType = 'Info Chased');
Now the nested SELECT statement currently returns NULL because there are initially no entries in tblActionLinks, and I am wondering if that is the issue.
The outer SELECT statement if executed on its own does return all the Diary Types from tblDiaryTypes as expected. But when I add the nested SELECT statement to exclusde certain values, then the overall SQL statement returns empty!
Does this have something to do withthe fact that tblActionLinks is currently empty? If so, how can I amend my SQL statement to handle that possibility.
For SQL SERVER (you didn't specified sql engine) try with:
SELECT ISNULL(NextDiary, 0) ...
When no rows found all value is null then it will return 0
Are you sure there are no entries currently in tblActionLinks? If there are no entries in tblActionLinks, then outer query should return all records
Does this have something to do withthe fact that tblActionLinks is currently empty?
Yes... NULL doesn't being handled so good in SQL, Comparing a value to NULL is undifned try give for null a flag value like -999:
SELECT DiaryType
FROM tblDiaryTypes
WHERE DiaryType NOT IN (SELECT NVL(NextDiary, -999) -- <===
FROM tblActionLinks
WHERE HistoryType = 'Info Chased');
NVL(NextDiary, -999) means that if NextDiary IS NULL, replace the value with -999
docs
I would rewrite your query the following way:
SELECT DiaryType
FROM tblDiaryTypes
WHERE NOT EXISTS (SELECT NextDiary
FROM tblActionLinks
WHERE HistoryType = 'Info Chased'
AND NextDiary = DiaryType)
This ensures proper behaviour irrespective of ANSI_NULLS setting and you don't have to worry about properly choosing the magic value returned by ISNULL(NextDiary, 0) (what if you have DiaryType equal to 0 in tblDiaryTypes?)