sql server queries related to case statement - sql

My query like this
case when statement1 = statement2 then offer1
if offer1 is have value means then i need to display offer1 value will be 'Yes'
How to write the query for this?

You can nest multiple CASE expressions like so:
CASE
WHEN statement1 = statement2
THEN
CASE WHEN offer1 IS NOT NULL THEN 'Yes' ELSE ... END
END

You can use Stored procedures and return a value depending on the conditions you need, in the stored procedures you can design your conditions using normal if statements, take a look at this example from here:
Create procedure dbo.Prc
#Value varchar(50),
#Result bit OUTPUT
AS
Begin
If exists (select 1 from YourTable where Field=#Value)
set #Result=1
Else
set #Result=0
End

Related

SQL Server stored procedure dynamic SQL in WHERE clause

I have written a stored procedure that accepts one parameter.
Request_ID int = 0
Later, in my WHERE clause, I need to accomplish the following.
I don't know how to describe it, but you can see what I'm trying to do with this completely made up pseudo-code:
WHERE isNull(a.Target_Department, '') <> ''
AND isNull(a.Resolved_Date, '') = ''
AND isNull(c.Request_Archived, '') <> 'Y'
AND IF #Request_ID = 0
THEN Request_ID > 0
ELSE Request_ID = #Request_ID
END
Basically, if a specific request_ID is supplied, I want the WHERE clause to narrow to only that specific Request_ID. Otherwise, I want all of them.
Any ideas on how to accomplish this?
Try this -->
WHERE
(#Request_ID IS NULL OR Request_ID=#RequestID)
OR
WHERE
(#Request_ID=0 OR Request_ID=#RequestID)
and isnull(nullif(#RequestId,0),RequestId)=RequestId

Using mixture of IF ELSE and OR in an SQL CASE statement

Just want to confirm, if this is the correct way in using IF ELSE OR statement in SQL?
CASE DB_NAME() WHEN 'dbName' THEN 'value1' ELSE 'value2-a' OR 'value2-b'
Basically i want to make a statement where if the dbName is correct, then it will take value1, else it will take either value2-a or value2-b.
I want to implement this statement in my stored procedure.
SQL Server does not have an if else or option. Each item in a select statement needs to evaluate to one value. You can't get two unique values for one field.
If you want to have multiple options in a CASE WHEN statement you can reuse the WHEN keyword.
For Example
SELECT CASE WHEN DB_NAME() = 'PROD' THEN value1
WHEN DB_NAME() = 'DEV' THEN value2-a
ELSE value2-b END DbValue
There are two types of CASEs, simple and searched. You can use both together. When a CASE without the optional ELSE falls through it returns NULL. Try something like this:
SELECT...
FROM...
WHERE
CASE DB_NAME() -- simple case
WHEN 'dbName' THEN
CASE value WHEN 'value1' THEN 1 END -- simple case
ELSE
CASE WHEN value IN ('value2-a', 'value2-b') THEN 2 END -- searched case
END IS NOT NULL
or this:
SELECT
CASE DB_NAME() -- simple case
WHEN 'dbName' THEN
CASE value WHEN 'value1' THEN value END -- simple case
ELSE
CASE WHEN value IN ('value2-a', 'value2-b') THEN value END -- searched case
END AS value
FROM...
There is more on CASE on MSDN.
I suspect you want logic like this:
WHERE (db_name() = 'prod' and value = 'value1') OR
(db_name() <> 'prod' and value in ('value2-a', 'value2-b'))

Execute a stored procedure within a case statement

I have an Insert Into Select statement with a Case When clause. I want to execute a stored procedure within the When statement.
Insert into Orders(id, custId, custIntake)
Select id, custId custIntake =
Case
When ( Exec mySProc(custId) = 1 ) = 'InStore'
When ( Exec mySProc(custId) = 0 ) = 'OutsideStore'
Else null
End
From OrdersImport
How can I run Exec mySProc(custId) within the Case When?
I would suggest you convert your 'mySProc' procedure into a Scalar User Defined Function if you want to run it like this. Stored Procedures are not able to do what you want.
If I understand correctly then what you need is code to run when the WHEN statement is true.
Just use CASE > WHEN > THEN as described here: http://msdn.microsoft.com/en-us/library/ms181765.aspx
Hope this helps.
Do like this.
If you set auto increment for id column, not need to mention in the query. If you need, you can add it.
Insert into orders(custId, custIntake)
Select custId, (CASE WHEN custId = '1' THEN 'InsideStore' ELSE 'OutsideStore' END) from ordersimport;
Hope, it will help you.

SQL Determine if parameter has a value

How would I go about using an IF statement to determine if more than one parameter has a value then do some work, if only one parameter has a value then do other work. Is this possible with the SQL if? I am just trying to determine if one parameter has a value or if multiple parameters has value, because if so then I need to do something completely different. I have tried making a SQL statement but it didnt work properly. Could anyone point me in the right direction?
In SQL to check if a parameter has a value, you should compare the value to NULL.
Here's a slightly over-engineered example:
Declare #Param1 int
Declare #param2 int = 3
IF (#Param1 is null AND #param2 is null)
BEGIN
PRINT 'Both params are null'
END
ELSE
BEGIN
IF (#Param1 is null)
PRINT 'param1 is null'
ELSE
IF (#Param2 is null)
PRINT 'param2 is null'
ELSE
PRINT 'Both params are set'
END
You can check the parameter values for NULL values. But it seems like to me at first blush you should check the parameters BEFORE going to the SQL...
Once you know what you need to do then call that SQL or Stored Procedure.
If you do it that way you can simplify your SQL because you only pass the parameters you really need to pass.
Actually the more I think of this the more important it is to do it this way. You can use the NULL values for other things that way.
Easy example: Getting a list of employees. Employees are Active or Inactive - Pass an #IsActive boolean parameter (if true only show active employees, if false show only inactive employees, if NULL then show all the employees)
In T-SQL you can use ISNULL function.
Here's an example
if #param1 = 'this value' and #param2 = 'another value'
begin
-- do things here
end
else if #param1 = 'something else'
begin
-- do other work
end
else
-- do different things
The answer provided by #Catch22 is good for your question. But using IFs in particular and procedural routines in general in sql should be kept to a minimum. So maybe the following solution using a case statement might better fit what you want to do:
select Case When #Param1 is null and #Param2 is null Then ...-- both params null
When #Param1 is null then .... -- param1 is null
When #Param2 is null then .... -- param2 is null
Else .... -- both params set
End

SQL Query...nulls hosing me

I tried to ask this question before but I don't think I explained myself very well. So here it is: asp.net 2.0 app hitting a SQL 2008 backend. This seems simple but I can't get it. 1 table. The user selects a status. The query should return all records = the chosen status only. If the user select "All Status", then ALL records should be returned, including those with a status = null (which is the part that is hosing me).
Ex:
CASE 1: User selects Status = "Satisfied"; ONLY satisfied records are return
CASE 2: User selects All Status = everything is returned, satisfied AND nulls and anything else
I tried passign in a wildcard but this doesn't return nulls. I tried dynamically buildign the query but I would like to avoid it.
For the case where you want them all, how about: (am I missing something?)
SELECT * FROM <tablename>
SELECT * FROM <tablename> WHERE Status = '*' OR Status IS NULL
...or '%' or whatever wildcard your SQL implementation uses.
...or if you really have no other conditions following this, just select *...
Try this in a stored procedure.
--Pass in #status as a parameter
DECLARE #Status varchar(100)
IF #Status = 'All Status'
BEGIN
SELECT * FROM tablename
END
ELSE
BEGIN
SELECT * FROM tablename where statusfield = #Status
END
One option is
declare #status varchar(50)
SELECT * FROM <tablename> WHERE (#status is null) or (Status = #status)
if you pass null in for the #status parameter then it will return all records. If you pass 'satisfied' or whatever then it will return just those matchng records.
If doing this in SQL 2008, be sure you have SP1 and Cumulative Update 5 installed. Further, I would recommend adding the WITH RECOMPILE option to the procedure. Under those conditions it will be as performant as embedded SQL or even using unions.
See the following article for an indepth discussion of the myriad of ways to perform searching in SQL 2008: Dynamic Search Conditions in T-SQL
The problem is that SQL's = operator always returns NULL when one of the operands is NULL, so using status = '%' indeed doesn't work. The best method is to just not include a condition on status if you want all of them. You can add extra NULL tests to the query, but that again is building it dynamically, I don't see a way to avoid that...
basically your statement will be for 'Statisfied'
SELECT * FROM testtab WHERE
COALESCE(statuscolumn, '') LIKE '%Statified'
for 'All Status' it will be
SELECT * FROM testtab WHERE
COALESCE(statuscolumn, '') LIKE '%'
you could use this statment and if selection is 'All Status' then pass a '' for the #status from your UI
SELECT * FROM testtab WHERE
COALESCE(statuscolumn, '') LIKE '%' || #status
Or you can use this one and when you pass the selection from UI make sure it has a '%' (wild char) appended to your status when it not 'All Status'. When its 'All Status' just pass '%' for the #status
SELECT * FROM testtab WHERE
COALESCE(statuscolumn, '') LIKE #status
oh your db is mssql? :) then you will need to replace the collace(statuscolumn, '') with isnull(statuscolumn, '').
Just skip the where clause or the part that is about the status field, example:
SELECT * from table_1 Where status = 'Satisfied'
and
SELECT * from table_1
When you want all records, you have to exclude STATUS from your WHERE clause (or use a UNION and a select statement where STATUS IS NULL).
Depending on what version of SQL you are using, you might be able to use an IF..ELSE... statement.
IF Status='ALL' THEN
... A SELECT statement where STATUS is NOT included in the WHERE
ELSE
... A SELECT statement that has a WHERE with only the status you are looking for
SELECT * FROM <tablename> WHERE isnull(Status,'*') = '*'
Assuming you're passing a variable to an SP:
SELECT * FROM Table WHERE Status CASE #status WHEN 'All status' THEN Status ELSE #status END
Otherwise, you need to concatenate in the selected value within quotes at both places where it currently says #status
The idea is what to do when the users chooses 'All Status'. By setting the param to NULL, you can use the isnull and then each [status] field just needs to equal itself. I've used ISNULL to set to '' to avoid having NULL = NULL>
declare #param_choice varchar(25)
if #param_choice = 'All Status'
Begin
#param_choice = NULL
End
-- get your results
Select * from Some_Table
Where IsNull([Status], '') = IsNull(#param_choice, IsNull([Status], ''))
You'll get the best performance from:
IF #status IS NULL
BEGIN
SELECT t.*
FROM TABLE t
END
ELSE
BEGIN
SELECT t.*
FROM TABLE t
WHERE t.status = #status
END
The next option is to use:
SELECT t.*
FROM TABLE t
WHERE (#status IS NULL OR t.status = #status)
...but that is not sargable.
I do not believe that anyone suggested using a UNION.
SELECT t.*
FROM TABLE t
WHERE (#status IS NULL)
UNION ALL
SELECT t.*
FROM TABLE t
WHERE (t.status = #status)
If #status is NULL, then the first query in the union is executed, and t.status = #status is clearly always false, so the second query in the union is not executed at all.
If #status is not null, then the first query in the union is not exected at all, and the second one is.
Importantly, since ISNULL, COALESCE or a function are not used on t.status or on #status, then if there is an index on status, it can be used. That is, the predicate is SARGABLE.
And I used UNION ALL (instead of UNION) to prevent a SORT and DISTINCT operation that can be very slow.