SQL Server : only display results of stored procedure under certain conditions - sql-server

I'm currently working on a stored procedure that creates a table with many columns with many conditions. One of the requirements of this proc is that when column A has a value of YES then Column B must have a value. I have no idea how to code this but I was leaning towards a case statement in the where clause along these lines
CASE WHEN Table.A = 'YES' then Table.B is not NULL end

You can transform it to
Where (Table.A = 'YES' and Table.B is not NULL)
OR Table.A <> 'YES'
May be you should add the full query to get it added in right way to the query

I'm assuming you need to include other logic in your process, which you can achieve by nesting case statements like the below. If not, Prdp's answer will be sufficient for your needs.
where case when Table.A = 'YES'
then case when Table.B is not null
then 1
else 0
end
else 0
end = 1

Related

Conditional Update Statement returning incorrect results on SQL Server 2012

I'm trying to update a table in SQL Server 2012 Management Studio. Rather than writing four separate Update statements, I'm attempting to see if it is possible to write one query that will update the same table for one column in four different ways depending on what the value of a column stores.
Assume I have a table called table_food with the following structure
|Customer|Preference|
+--------+----------+
|John |McDs |
|Div |KFC |
|Paul |KFC |
|Pablo |Wasabi |
My idea is to update the Preference column to new values and the query I had written was:
UPDATE table_food
SET Preference =
CASE WHEN Preference = 'McDs' Then 'Burger'
WHEN Preference = 'KFC' Then 'KingsMeal'
END
Now on my actual table, there are only 8 different options selected for preference and I just need two update 4. (I've just done two as an example above but I have four when statements...so just another two lines)
When I run the query it shows far more rows being affected and checking the results after I notice now there's only one option shown "Burger" with a count of 8 and all the other rows have been set to null. Is there something I'm missing?
That query will update every row on your table since it lacks a WHERE clause. And a CASE WHEN expression returns NULL if none of the WHEN conditions are true. You might want a query like:
UPDATE table_food
SET Preference =
CASE WHEN Preference = 'McDs' Then 'Burger'
WHEN Preference = 'KFC' Then 'KingsMeal'
END
WHERE Preference in ('McDs','KFC')
add else on your case statement.
UPDATE table_food
SET Preference =
CASE WHEN Preference = 'McDs' Then 'Burger'
WHEN Preference = 'KFC' Then 'KingsMeal'
ELSE Preference
END
or if you only want to update affected rows, you do update from
UPDATE table_food
SET Preference = t2.newPreference
FROM
(SELECT CASE WHEN Preference = 'McDs' Then 'Burger'
WHEN Preference = 'KFC' Then 'KingsMeal'
WHEN Preference = 'KFC1' Then 'KingsMeal1'
WHEN Preference = 'KFC'2 Then 'KingsMeal2'
END as newPreference, Preference
FROM table_food) t2
WHERE t2.Preference = table_food.Preference and coalesce(t2.newPreference, '') != ''

Conditionally include a line in a T-SQL WHERE clause

Honestly, I've gone over other questions posted here that mention conditional where clauses and I'm not seeing any answers that seem to work for my situation. If one does, please point me to it!
In a stored procedure called by an SSRS report, the user can select one of two values in a dropdown - say "Yes" or "No" and that goes into the variable #color.
In the WHERE clause of the sproc I need to filter differently depending on the user's selection.
So, if #color = 'Yes', then I need to have a line in the WHERE clause that reads something like tb1.somecolumn = 'BLUE'. But if #color = 'No' then I don't need that line in the where clause at all (tb1.somecolumn can be any value).
How do I conditionally include a line in the WHERE clause?
Include the check for #color in the WHERE as follows.
WHERE (#color = 'No')
OR (#color = 'Yes' AND tb1.somecolumn = 'BLUE')
Explanation:
If the value of #color is 'No', then all rows are returned.
If the value of #color is 'Yes', then only the 'BLUE' rows are returned.
Try following condition
WHERE (#color = 'Yes' AND tb1.somecolumn = 'BLUE')
OR (#color = 'No' AND tb1.somecolumn = tb1.somecolumn)

How to design an errors table for data validations in a star schema

I am working in SQL Server 2008. I have been tasked with writing a stored procedure to do some data validations on external data before we move it into our star schema data warehouse environment. One type of test requested is domain integrity / reference lookup from our external fact data tables to our dimension tables. To do this, I use the following technique:
SELECT
some_column
FROM some_fact_table
LEFT JOIN some_dimension_table
ON
some_fact_table.some_column = some_dimension_table.lookup_column
WHERE
some_fact_table.some_column IS NOT NULL
AND
some_dimension_table.lookup_column IS NULL
The SELECT clause will match the column definition for an errors table that I will eventually move the output into via SSIS. So, the SELECT clause actually looks like:
SELECT
primary_key,
'some_column' AS Offending_Column,
'not found in lookup' AS Error_Message,
some_column AS Offending_Value
But, because the fact tables are very large, we want to minimize the number of times that we have to select from it. Hence, I have just 1 query for each fact table to check each column in question, which looks something like:
SELECT
primary_key,
'col1|col2|col3' AS Potentially_Offending_Columns,
'not found in lookup|not found in lookup|not found in lookup' AS Error_Messages,
col1 + '|' + col2 + '|' + col3 AS Potentially_Offending_Values
FROM fact_table
LEFT JOIN dim_table1
ON
fact_table.col1 = dim_table1.lookup_column
LEFT JOIN dim_table2
ON
fact_table.col2 = dim_table2.lookup_column
LEFT JOIN dim_table3
ON
fact_table.col2 = dim_table3.lookup_column
WHERE
dim_table1.lookup_column IS NULL
OR
dim_table2.lookup_column IS NULL
OR
dim_table3.lookup_column IS NULL
This has some problems with it. (1) If any of the source column rows is null, then the string concatenation in Offending_Values will result in NULL. If I wrap each column with ISNULL (and swap the nulls for something like an empty string), then I won't be able to tell if the test failed because of a true empty string in the source or if it was swapped for an empty string. (2) If just one of the columns fail in the lookup, then the error message will still read 'not found in lookup|not found in lookup|not found in lookup', i.e., I can't tell which of the columns actually failed. (3) The Potentially_offending_Columns column in the output will always be static, which means I can't tell if any of the columns failed just by looking at it.
So, in effect, I am having some design problems with my errors table. Is there a standard way of outputting to an errors table in this situation? Or, if not, what do I need to fix to make the output readable and useful?
I don't know what your data looks like, but instead of using an empty string with ISNULL, couldn't you return the word FAIL or something that's meaningful to you. You could do a CASE WHEN for your 'not found in lookup' column.
CASE WHEN Col1 IS NULL THEN 'not found in lookup' ELSE '' END + '|' +
CASE WHEN Col2 IS NULL THEN 'not found in lookup' ELSE '' END + '|' +
CASE WHEN Col3 IS NULL THEN 'not found in lookup' ELSE '' END AS Error_Messages,
ISNULL(col1,'FAIL') + '|' + ISNULL(col2,'FAIL') + '|' + ISNULL(col3,'FAIL') AS Potentially_Offending_Values

How to use If Else Condition in Where Clause in SQL Server for Date Columns?

I want to use if else in where condition for Date Coulmns. Actually what i want to do is:
I have a table, which having two columns, CreatedDate and LastModifiedDate. Now what i want to check in Stored Proc is:
if LastUpdateDate is null then it will check for CreatedDate.
Below is my query:
SELECT isnull(SSA.UpdateDateTime,
isnull(SSA.CreateDateTime,'')) as LastUpdateAnswerDateTime
from SI_SurveySiteAnswer SSA
WHERE SSA.UpdateDateTime IS NOT NULL
There are other number of table in joins i am just pasting the required query only. how can i go for the check i am totally confused.
Please help me..
UPDATED:
I have write the below code, please confirm if it is the correct way to use If in where
SELECT isnull(SSA.UpdateDateTime,
isnull(SSA.CreateDateTime,'')) as LastUpdateAnswerDateTime
from SI_SurveySiteAnswer SSA
WHERE SSA.UpdateDateTime = ISNULL(SSA.UpdateDateTime,SSA.CreateDateTime)
I think i was not able to make my requirement very clear in first go, let me explain here..
i have a survey question answer table, i want to send an email notification if question has been answered, now answer can answered in one go, in that case createddate will have value not the updateddatetime,
Second case is:
answer is being updated in second go, then i need to check for the LastUpdateDateTime..
That's what i want to make in query.
You don't need any if / else functionality, just use the or operator to check that either is not null:
WHERE SSA.CreateDateTime is not null OR SSA.UpdateDateTime is not null
You can use COALESCE if you want this functionality, here are some sites for your reference.
http://www.mssqltips.com/sqlservertip/1521/the-many-uses-of-coalesce-in-sql-server/
http://sqlmag.com/t-sql/coalesce-vs-isnull
you can use case
SELECT Isnull(SSA.updatedatetime, Isnull(SSA.createdatetime, '')) AS
LastUpdateAnswerDateTime
FROM si_surveysiteanswer SSA
WHERE SSA.updatedatetime = CASE
WHEN SSA.updatedatetime IS NULL THEN
#SSA.createdatetime
ELSE SSA.updatedatetime
END
Try case statement.
SELECT isnull(SSA.UpdateDateTime,
isnull(SSA.CreateDateTime,'')) as LastUpdateAnswerDateTime
from SI_SurveySiteAnswer SSA
WHERE CASE WHEN SSA.UpdateDateTime IS NULL THEN SSA.CreateDateTime
ELSE SSA.UpdateDateTime END IS NOT NULL

Switch case in where clause (sql server)

I want to use case in sql statement where clause but I have a problem as I want to create a where clause condition on the basis of some value and I want to set a not in clause values on the basis of it
here is the query where am facing an issue
WHERE CODE = 'x' and
ID not in (
case
when 'app'='A' then '570','592'
when 'Q' then ID 592,90
else 592,90
END
but its not syntax
You could embed it into the SQL where clauses like this:
WHERE CODE='x' and (('app' = 'A' AND ID not in ('570', '592')) OR
('app' = 'Q' AND ID not in ('592','90')) OR ('app' != 'A' AND 'app' != 'Q' AND ID not in ('592','90'))
Or something like that. Creepy code though, so I'd suggest using different queries for different types of 'app' parameter or create a stored procedure to handle your needs.
Consider that you may be trying to combine what should actually be separate statements.
You may want to consider using a test condition (perhaps via a simple IF statement) to determine which specific T-SQL statement to actually execute.
Pseudo Code:
IF (/*Conditions are True*/)
BEGIN
--SQL Statement
END
ELSE IF (/*Some other conditions are True)
BEGIN
--SQL Statement
END
ELSE
BEGIN
--Failsafe SQL statement
END
The logical intent of the code produced will be much easier to understand and maintain going forward.
As 592 is always part of the set, and the "Q" case is the same as the default, just do like this:
where CODE = 'x' and ID not in (592, case app when 'A' then 570 else 90 end)

Resources