SQL - Use different Select Statements based on column value - sql

For instance,
Select field1
From table1
when table1.field1 = 'S'
then (select field1,2,3,4,5,6,.....
form table1,2,3,4,5,6,....(with joins))
when table1.field1 = 'O'
then (select field1,2,3,4,5,6,.....
from table1,2,3,4,5,6,.....(with join))

I think I got what you need. One possible solution is to create a view with hardcoded where clauses on it. This is the idea:
CREATE VIEW ConditionalSelect AS
SELECT ...fields...
FROM ...tables...
JOIN ...joins...
WHERE table1.field1 = 'S'
AND ....
UNION
SELECT ...fields...
FROM ...tables...
JOIN ...joins...
WHERE table1.field1 = 'O'
AND ....
Then you can do this:
SELECT *
FROM ConditionalSelect
WHERE field1 = 'S'
NOTE: Both SELECT MUST have the same columns, columns types and column names, either the VIEW won't compile.

You could just do something like this:
DECLARE #Field1 VARCHAR(10) =
(
SELECT Field1
FROM table1
);
IF(#Field1 = 'S')
BEGIN
SELECT *
FROM table1 t1
INNER JOIN table2 t2
ON t2.col1 = t1.col1
END
ELSE IF (#Field1 = 'O')
BEGIN
SELECT *
FROM table1 t1
INNER JOIN table2 t2
ON t2.col1 = t1.col1
END
Saves you from creating a view

Related

UPDATE with isNull

In Microsoft SQL Server,
if the inner select doesn't have a matching criteria, then I need to update Field1 with blank instead of null.
UPDATE Table1
SET Field1=(
SELECT Field2
FROM Table2
WHERE Table2.Field3 = Table1.Field4
)
Please try like this -
UPDATE a
SET a.Field1 = ISNULL(b.Field2,'')
FROM Table1 a
LEFT JOIN Table2 b ON b.Field3 = a.Field4
You can reference another table using SQL Server's UPDATE ... FROM ... syntax:
UPDATE t1
SET field1 = COALESCE(t2.field2, '')
FROM Table1 t1
LEFT JOIN
Table2 t2
ON t2.Field3 = t1.Field4
The COALESCE() function returns the first non-null expression in a list. You can keep most of your original query, by using COALESCE() to replace any NULL from that query with an empty string.
UPDATE Table1
SET Field1=COALESCE((
SELECT Field2
FROM Table2
WHERE Table2.Field3 = Table1.Field4
), '')
Try this
UPDATE T1
SET T1.Field1=isnull(T2.Field2,'')
from Table1 T1 left join Table2 T2
ON T2.Field3 = T1.Field4

How to use a field name as an argument for a nested select statement

I'm trying to do something wonky, but I cant think of any other way to do it:
SELECT
my_table.field1 as field1,
(EXISTS (SELECT 1 FROM another_table WHERE id = field1)) as does_exist
FROM my_table
This obviously fails because field1 doesn't exist at the time the result set is created. Does anyone know how to accomplish this?
You can use left join:
select distinct on (t1.field1) t1.field1, t2.id is not null as does_exist
from my_table t1
left join another_table t2 on t2.id = t1.field1
however your query should work as well:
SELECT
my_table.field1 as field1,
(EXISTS (SELECT 1 FROM another_table WHERE id = my_table.field1)) as does_exist
FROM my_table
SELECT
my_table.field1 as field1,
case another_table.ID
when null then 0
else 1
end does_exist
FROM my_table
left outer join another_table on another_table.ID = my_table.field1
Here 1 is Exists, and 0 not exists

Select boolean result of whether a value exists or not

Select FieldA, " if data exists in table two return true else false "
from Table1
Left join Table2 on Table1.Id=Table2.Id
This is how I currently do the requirement above:
Select FieldA, (case when Table2.Table2Id is not null then 1 else 0 End)
from Table1
Left join Table2 on Table1.Id=Table2.Id
Is there any replacement for the "Case" statement, to something like ifExists(Table2.Id) ?
You can use EXISTS, i guess you want the strings True/False, otherwise cast 1/0 to bit:
SELECT Id,
DataExists = CASE WHEN EXISTS
(
SELECT 1 FROM Table2 WHERE Table2.Id = Table1.Id
) THEN 'True' ELSE 'False' END
FROM dbo.Table1
For the sake of completeness:
SELECT Id,
DataExists = CAST((CASE WHEN EXISTS
(
SELECT 1 FROM Table2 WHERE Table2.Id = Table1.Id
) THEN 1 ELSE 0 END) AS BIT)
FROM dbo.Table1
May be you can use isNull as well.
Select FieldA, isnull((SELECT 'TRUE' FROM TABLE2 WHERE TABLE2.ID = TABEL1.ID),'FALSE') AS columName
from Table1

Need to simplify multiple Select queries

This is the structure of my existing SQL query :
SELECT * FROM (
SELECT *, 'A' AS Status FROM Table1
WHERE Field1 NOT IN
(
SELECT Field1 FROM Table2 WHERE Field 1 = 'val' AND ...
)
UNION
SELECT *, 'B' AS Status FROM Table1
WHERE Field1 IN
(
SELECT Field1 FROM Table2 WHERE Field 1 = 'val' AND ...
)
) AS Result
Here I'm selecting two sets of data from a table and assigning two different values (A & B) for the Status column and Union both sets in to one as Result.
Problem with this method is, it needs to duplicate the inner select query SELECT Field1 FROM Table2 WHERE Field 1 = 'val' AND ... (my original sql query is bit complex than the shown above)
How can I rewrite this as a single Select query? Is it possible or not?
You could simply move the WHERE condition to a CASE expression, like this:
SELECT
*,
CASE
WHEN Field1 IN (
SELECT Field1 FROM Table2 WHERE Field1 = 'val' AND ...
)
THEN 'B'
ELSE 'A'
END AS Status
FROM Table1
;
You could also use a LEFT JOIN method like others suggested, but if Table2 produces duplicates for the specified filter, you might get duplicates in the output as well. To avoid that, you would probably need to use a derived table that only returns distinct values, something like this:
SELECT
t1.*,
CASE
WHEN t2.Field1 IS NULL THEN 'A'
ELSE 'B'
END AS Status
FROM Table1 t1
LEFT JOIN (
SELECT DISTINCT Field1 FROM Table2 WHERE Field1 = 'val' AND ...
) t2
ON t1.Field1 = t2.Field2
;
you can simply use LEFT JOIN on this,
SELECT a.*,
CASE WHEN b.field1 IS NULL
THEN 'A'
ELSE 'B'
END AS Status
FROM table1 a
LEFT JOIN table2 b
ON a.field1 = b.field1 AND
b.field1 = 'VAL'
Please check the below query, which works if there is only one condition of Field1=’val’ on Table2. If there are multiple where conditions, then go for LEFT JOIN.
SELECT
*,
(CASE WHEN Field1='val' THEN 'B' ELSE 'A' END) AS Status
FROM
Table1
U can achieve this by using LEFT JOIN and CASE as follows
SELECT a.*,
(CASE b.Field1
WHEN 'Val'
THEN 'B' ELSE 'A' END) as status
FROM Table1 a LEFT JOIN Table2 b ON a.field1 =b.field1
If multiple conditions are there for status try the following one
SELECT a.*,
(CASE
WHEN (SELECT COUNT(Field1)
FROM Table2
WHERE field1 =a.field1 AND Field 1 ='val' AND ...) >0
THEN 'B' ELSE 'A' END) as status
FROM Table1 a LEFT JOIN Table2 b ON a.field1 =b.field1

SQL Server 2005 - Using CASE inside Stored Procedure

I'm using a select statement inside a stored procedure. All I need to do is based on the value of a parameter I've to use either RIGHT JOIN or INNER JOIN. Please anyone there help me to achieve this. Many Thanks in Advance..
SELECT FLD1, FLD2
FROM TBL1 C (NOLOCK)
CASE
WHEN #SHOW = 156 THEN INNER
ELSE RIGHT JOIN TBL2 IC (NOLOCK) ON C.FLD3 = IC.FLD4
END
Is it correct? What would be the right way of doing this?
You could use IF statements:
DECLARE #Param VARCHAR(10)
SET #Param = 'RIGHT'
IF (#Param = 'RIGHT')
SELECT t1.Something
FROM Table1 t1
RIGHT JOIN Table2 t2 ON t1.ID = t2.ID
WHERE ...
ELSE IF (#Param = 'INNER')
SELECT t1.Something
FROM Table1 t1
INNER JOIN Table2 t2 ON t1.ID = t2.ID
WHERE ...
Or could be done as one SELECT (not necessarily best performance, be sure to test), something like:
SELECT t1.Something
FROM Table1 t1
RIGHT OUTER JOIN Table2 t2 ON t1.ID = t2.ID
WHERE (#Param = 'RIGHT') OR (#Param = 'INNER' AND t1.ID IS NOT NULL)
Theres more than enough information on the case statement out there, this should get you started.