Single Select SQL Statement for 2 different Values - sql

I have a SQL Server table with a column called Category. In my user interface, I have a dropdown list of the category. User can select a category and click on a Search button to filter the results by the category. In the dropdown, the first option is blank. Means if the user wants to see all records from all categories, he can select blank.
In my SQL Select I have 2 statements for this
IF #Catg IS NULL
Begin
Select *
From Table
End
Else
Begin
Select *
From Table
Where Catg = #Catg
End
The Catg column in the table will have either a NULL or a category. Is this possible to do in a single SQL statement?

You can use an OR statement to join the clauses together:
Select *
From Table
Where Catg = #Catg OR #Catg IS NULL

How about
SELECT *
FROM yourtable
WHERE (Catg = #Catg) OR (Catg IS NULL)

might be ISNULL solve your problem this will check if values is NULL then '' else your VALUE
select * from tblName
where ISNULL(Catg , '')= ISNULL(#Catg, ISNULL(Catg , ''))

Related

SQL if column is empty, add an empty column

I want to be able to check if we have a column and if not, then we just want to add an empty column,
IF Users.[parties] = '' OR NULL
BEGIN
SELECT [parties]
FROM Users
UNION
SELECT 'Empty'
END
The Users.[parties], we check to see if we have a column but if we don't, it will result in a crash, in the case for this event I thought it would be best just to add an empty column with the name of Empty but I can't get the code to work above.
If we do have columns, the results will be something like...
ColumnsName ColumnAge
data 33
data 22
But when there isn't a column, it crashes and ideally I would like it to just have an empty column like this,
EmptyColumn
The code below checks whether a column exists in the table, in our case the name of the column is columnName and the name of the table is tableName.
IF COL_LENGTH('schemaName.tableName', 'columnName') IS NOT NULL
BEGIN
-- Column exists
SELECT [parties] FROM Users
END
ELSE
BEGIN
-- Column does not exists
SELECT 'Empty'[parties]
END
I think you just want
IF EXISTS(
SELECT 1
FROM Sys.Columns
WHERE Name = N'parties'
AND
Object_ID = Object_ID(N'SchemaName.Users')
)
BEGIN
SELECT parties
FROM Users;
END
ELSE
BEGIN
SELECT 'EmptyColumn' EmptyColumn -- or NULL EmptyColumn
FROM Users;
END
I'll try with this: (I'm not sure it works)
select case when ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) =0 --count rows
then 'empty' -- if 0 output empty
else parties end as parties --else ouputs the result
from your_table
This is a more 'standard' approach
CREATE VIEW user_filled as
SELECT [parties]
FROM Users
UNION
SELECT 'EMPTY'
and when you query it (if needed -> on count(*))
select count(*)
from user_filled
where parties <> 'EMPTY'
on join
select *
from user_filled join other_table
on (user_filled <> 'EMPTY and userfilled.key= other_table.key)
NOTE: put the clause into the ON so it's filtered out BEFORE the join is made

SQL AND Clause only if another value exists

I have a basic SQL query where I am selecting data from a core records table. I want to add an AND clause to my statement to filter out the results based on a table variable, only if data actually exists in there.
SELECT
*
FROM
TABLE
WHERE
field = '123'
AND
(gender IN (SELECT gender FROM #genders))
In this case, I am looking for all records where field = 123. My goal here is to say that if #genders contains records, filter by that as well.
However, if #genders is empty and we don't have any data in it, it should include all records.
How can I go about doing this? The temp tables are created based on the user selecting one or more optional pieces of criteria from the UI. If they choose a gender for example, I put their selections into a temp table and then I need to search records that meet that criteria. However, if they don't select a gender, I want to include all records, regardless of what the main record has for the gender field.
SELECT
*
FROM
TABLE
WHERE
field = '123'
AND ((SELECT count(1) FROM #genders) = 0 OR
(gender IN (SELECT gender FROM #genders)))
You can use IF condition:
IF EXISTS(SELECT gender FROM #genders)
BEGIN
SELECT * FROM TABLE
WHERE field = '123'
AND
(gender IN (SELECT gender FROM #genders))
END
ELSE
BEGIN
SELECT * FROM TABLE
END
You are going to think this is odd but it is efficient
SELECT t.*
FROM TABLE t
JOIN GENDERS g
on g.gender = t.gender
and t.field = '123'
union all
SELECT t.*
FROM TABLE t
where not exists (select 1 from genders)
Maybe I'm under-thinking it, but isn't it just this?
SELECT
*
FROM
TABLE AS t
LEFT JOIN
#genders AS g
ON
g.gender = t.gender
WHERE
field = '123'
AND
(g.gender = t.gender OR g.gender IS NULL);
If your query doesn't get too complicated, I'd recommend an if statement. Once you find yourself continually adding if else statement in there, I'd recommend looking into dynamic SQL.
IF EXISTS(SELECT gender FROM #genders)
BEGIN
SELECT * FROM TABLE
WHERE field = '123'
and gender IN (SELECT distinct gender FROM #genders)
END
ELSE
BEGIN
SELECT * FROM TABLE WHERE field = '123'
END

How to limit the columns of the select statement?

I have to create a new table and inside should be the columns I get from the CASE statement. I do not need the rest of the columns resulting from the select statement
for example:
CREATE TABLE test
AS (
SELECT a.id, ...
CASE WHEN a.id = 1 THEN 2
ELSE 0
END as LegalType
FROM table a, ...
WHERE ...);
now my question how can I select only the column LegalType from the CASE statement? I do not want to have column a.id
You can SELECT INTO
SELECT CASE WHEN a.id = 1 THEN 2 ELSE 0 END as LegalType
....
INTO test
FROM table a
WHERE 1=1);
This will create you a table based on the data returned in the SELECT. see https://msdn.microsoft.com/en-GB/library/ms188029.aspx

conditional select stmnt in table query ssrs 2005

I am using SSRS 2005 using SQL Server.
I have 2 tables:
Order - contains open (unshipped) orders
Order_History - contains closed (shipped and invoiced) orders
I am using a UNION ALL to get data from both tables. However, I would like to add 1 multivalue parameter OrderType with "open", "closed", "both" for the values so the user can say they ONLY want open, ONLY want closed, or BOTH.
Is there a way in the the dataset query (that the table uses) to put an IF or CASE so that the query runs only one select statement depending on what's chosen?
IN other words, something like:
"IF (#OrderType) = 'OPEN' select field a,b from Order;
ELSEIF (#OrderType) = 'CLOSED' then select field a,b from Order_History;
Else select field a,b from Order UNION ALL select field a,b from Order_History".
You could add a column to both selects in the UNION with 'open' and 'closed' respectively and then do an outer query around it to select only the values that you want with a case statement on the #orderType:
SELECT *
FROM (
SELECT *, 'open' AS STATUS
FROM order
UNION ALL
SELECT *, 'closed'
FROM Order_History
) a
WHERE STATUS = CASE
WHEN #OrderType = 'both' THEN STATUS
ELSE #OrderType
END;
sqlfiddle demo

How to summarize SQL table to return value conditionally

I have a table with several rows, and several columns. It looks like this:
Name Description
X PASS
X PASS
X FAIL
I want it to return only one row. If all of them are PASS, return PASS.
If one or more of them are FAIL, then return FAIL.
What's the best way to go about achieving this in SQL Server 2008?
EDIT: The values in the name column will always be the same.
Depending on the database indexes, and assuming you want one row returned per unique name, I would look at the performance of
select
name,
min([description]) as description
from
tableA
group by
name
compared to the other solutions
SELECT TOP 1 CASE Description WHEN 'FAIL' THEN 'FAIL' ELSE 'PASS' END
FROM DaTable
ORDER BY Description
OP: Is it possible that the table is empty? In that case this query won't return any rows, obviously.
EDIT
According to aquinas's comment I created a modified query without ordering:
SELECT CASE COUNT(Description) WHEN 0 THEN 'FAIL' ELSE 'PASS' END
FROM DaTable
WHERE Description = 'FAIL'
This query will return PASS if DaTable is empty.
This is the simplest solution you will find:
SELECT MIN(Description) FROM tbl
If there's at least one FAIL, then our result column will contain FAIL, otherwise, it will contain PASS.
You can use EXISTS to get the existance of a row containing "FAIL".
You could also try something like:
SELECT TOP 1 COALESCE(tFail.Description,t.Description)
FROM myTable AS t
LEFT JOIN myTable AS tFail ON tFail.Name = t.Name AND tFail.Description = 'FAIL'
WHERE t.Name = 'x'
Here is the query:
--DROP TABLE result
CREATE TABLE result(Name varchar(10),Description varchar(20))
--select * from result
INSERT INTO result
VALUES('X','PASS'),('X','PASS'),('X','FAIL')
;WITH CTE(descp,cnt) as (SELECT [description],COUNT(*) as cnt FROM result group by [description])
SELECT CASE WHEN COUNT(*) > 1 then 'FAIL' when COUNT(*)=1 then MAX(descp) else 'PASS' END FROM CTE