SQL Determine if parameter has a value - sql

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

Related

Correct usage of WHERE and AND in procedure with optional parameters

Pre-question info:
I'm writing a stored-procedure that would take some parameters and depending on those parameters(if they are filled - because they don't have to be) I'm adding few where clauses. The thing is I don't know if I'm gonna even use the where clause from start because I don't know if any of my params is going to be non-empty/not-null.
The inside of procedure looks cca like:
BEGIN
DECLARE #strMySelect varchar(max)
SET #strMySelect ='SELECT myparams FROM mytable'
// add some WHERE statement(*)
IF(ISNULL(#myParamDate1,'')<>'')BEGIN
SET #strMySelect =#strMySelect +'
AND param1 >='''+CAST(#myParamDate1 as varchar(30))+''''
END
IF(ISNULL(#myParamDate2,'')<>'')BEGIN
SET #strMySelect =#strMySelect +'
AND param1 <='''+CAST(#myParamDate2 as varchar(30))+''''
END
//... bit more of these "AND"s
EXECUTE(#strExec)
QUESTION:
Is it ok(correct way of doing this) to put in my query some WHERE statement that I know that will be always true so I can use in my parameter cases AND always? OR do I have to check for each param if it's first one that is filled or is there an easy way of checking in SQL that at least one of my parameters isn't NULL/empty?
I handle optional parameters like this:
where (
(#optionalParameter is not null and someField = #optionalParameter )
or
#optionalParameter is null
)
etc
I find it simpler.
Your extra where clause is not a problem from a performance point-of-view, since the query optimizer will (likely) remove the 1 = 1 condition anyway.
However, I would recommend a solution along the lines of what Dan Bracuk suggested for two reasons:
It is easier to read, write and debug.
You avoid the possibility of SQL injection attacks.
There are cases where you have to custom-build your query-string (e.g. when given a table name as parameter), but I would avoid it whenever possible.
You don't need to use EXEC function to check for parameters. A good practice is using case to check for parameter value for example
CREATE PROCEDURE MyProc
#Param1 int = 0
AS
BEGIN
SELECT * FROM MyTable WHERE CASE #param1 WHEN 0 THEN #param1 ELSE MyField END = #Param1
END
GO
In case that #param1 has no value (default 0) then you have #param1=#param1 which gives always true, in case you have #param with value then condition is MyField=#param1.

SQL Server Stored Procedure WHERE Clause IF CASE No Value

I have a stored procedure with default values, which I set to NULL. In the WHERE clause, for each value specified, rather than NULL or not given (where it would also be NULL), I would like the column to equal this value, otherwise, I would like to search without this column being in the WHERE clause. The basic structure looks something like this:
// Set up the stored procedure
USE Table;
GO
CREATE PROCEDURE dbo.SearchTable
// Specify value(s)
#Name varchar(50) = NULL
AS
// Set up the query
IF(#Name IS NOT NULL
SELECT * FROM Table WHERE Name=#Name;
ELSE
SELECT * FROM Table
BEGIN
END
I have more than 1 parameter, and so, with this logic, I would need 2 IF's for every parameter. As you can imagine, this gets boring, time-consuming, and error-prone fast.
I would like to move this logic into the query, preferably into the WHERE clause, but any way I have found will cause errors (besides exceptions, which would require just as many IF's). SQL Server doesn't like IF's in the WHERE clause as far as I know, and with CASE I would have to specify the column, which I do not want to do.
What should I do?
Edit:
I have SQL Server version 2012, so please concentrate on this or any recent versions in your answer.
If you don't care about performance, you can do:
SELECT *
FROM Table
WHERE #Name is null or Name = #Name;
Often, having an or condition gets in the way of efficient use of indexes. Perhaps this isn't a problem in your case, though.
You could do something like this. The downside to this is that indexes may not be used properly and thus the performance may not be great.
SELECT * FROM Table
WHERE (#Name Is Null Or Name = #Name)
And (#Col2 Is Null Or Col2 = #Col2)
And (#Col3 Is Null Or Col3 = #Col3)
Each column condition is "anded". Or is used to apply that column condition only if #var is not null. So for example, if this is called with just #Name populated, it is equivalent to Where Name = #Name. If both #Name and #Col2 are populated, it is equivalent to Where Name = #Name And Col2 = #Col2.

How to check if a variable has a value in a SQL Server 2008 stored procedure

I need to check whether a variable has a value or not.
declare #name varchar(20)
set #name = (SELECT Product_Name
FROM tb_new_product_Name_id
WHERE Product_Name = #productName)
if (#name ) // here I need to check it
How to do it? thanks
Try this
if (#name is null or #value = '') //it will indicate whether it contains a value or not
Just do the IF directly, using EXISTS instead:
IF EXISTS(SELECT * FROM tb_new_product_Name_id
where Product_Name=#productName)
BEGIN
--Do something because a row existed with that name
END
We may be able to further assist with simplifying your code if you told us more on what you were planning to do having confirmed a row existed in tb_new_product_Name_id. It looks like you're writing very procedural code - first I'll do X, then I'll do Y, then I'll do Z, etc. SQL excels as a language where you tell it "what to do" - for the entire data set you want to compute - not "how to do it" in a step by step, row by row fashion.
IS NOT NULL
As NULL would indicate the absense of a value.
You can check if null using IS NULL as follows;
DECLARE #name VARCHAR(20)
SET #name = (SELECT Product_Name FROM tb_new_product_Name_id where Product_Name=#productName)
IF #name IS NULL -- # Here is where you check it
BEGIN
-- # Handle null #name
END
ELSE
BEGIN
-- # #name has value
END
This how i would do, but if you are declaring #name variable only for null checking then i would go as Demien_The_Unbeliever suggests. Using EXISTS you don't even need the #name variable
An uninitiated variable always has null value in it. You may use IS NOT NULL to check that..
Recently encountered a situation where a field with no values was being checked with is null, is not null but was not working and on debugging found if no value then the field was getting a 0. So checking for value = '' or value = 0 or value is null, one of the three would check if its empty.

sql server queries related to case statement

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

Perform an action within a stored procedure depending on the result of another action within the stored procedure?

I realise that this must be a very basic question, but my google-fu seems to be entirely absent at the moment.
What I want to do is, inside a stored procedure:
Declare a VarChar(1) variable, myVarChar
Search a table for the value of a corresponding VarChar(1), based on an incoming #myKey argument to the stored procedure, and assign its value to myVarChar
Perform one of two different Insert statements depending on the new value of myVarChar
As I say, I'm sure this must be quite straightforward, and I apologise for that, but I'm just not seeing the information I want in my searching.
declare #myVarChar varchar(1);
Select #myVarChar=MyCol From MyTable Where MyOtherCol = #myKey;
If #myVarChar = 'A'
Begin
End
Is this what you are looking for?
Use this general format:
IF #variable = 'foo'
BEGIN
<do some stuff>...
END
IF #variable = 'boo'
BEGIN
<do some other stuff>...
END
IF #variable = 'neither foo nor boo'
BEGIN
<do whatever you want as a failsafe>
END