Use ISNULL or "LIKE" - sql

I have a stored procedure which takes in a few parameters which could be NULL or maybe not.
I can use the ISNULL option if I have a clear value for a parameter, but if I want to use a "LIKE" instead of null I'm not sure how to do it. See below:
Parameters are:
#org_id as int,
#deleted as bit = NULL,
#firstname as char = NULL,
#lastname as char = NULL
Select statement is:
select user_id, firstname,lastname,firstname +' ' + lastname as fullname, email, phone, is_tech, is_admin,is_cust
from users
where users.org_id=#org_id and is_tech=1 and delete_flag=ISNULL(#deleted,delete_flag)
order by lastname,firstname asc
If the firstname and lastname params are not null, but are instead a character e.g."J" ,how can I write something similar to the delete_flag clause ..and firstname like 'J%' but if not use null?
Any ideas?

You can use this:
WHERE field LIKE #param OR #param IS NULL

Related

WHERE clause using values that could be NULL

I need to do something like this:
DECLARE #firstname VARCHAR(35)
DECLARE #lastname VARCHAR(35)
SELECT *
FROM Customers
WHERE Firstname = #firstname AND Lastname = #lastname
The problem is that #firstname and #lastname could sometimes be NULL. In those cases, the query above would fail to find matching rows because NULL is never equal to NULL.
If one of these variables is NULL, I'd like to return a match if the corresponding value in the database is also NULL. But, of course, SQL Server uses IS to compare for NULL. And if either value is NULL in the example above, it is not considered a match.
Is there any way to accomplish this?
Just use AND/OR logic e.g.
SELECT *
FROM Customers
WHERE ((Firstname IS NULL AND #firstname IS NULL) OR Firstname = #firstname)
AND ((Lastname IS NULL AND #lastname IS NULL) OR Lastname = #lastname);
You can leverage INTERSECT in a correlated subquery to do this. This works because set-based operations compare NULLs as equal.
The compiler will automatically compile this down to an IS comparison, there should not be any performance hit.
DECLARE #firstname VARCHAR(35)
DECLARE #lastname VARCHAR(35)
SELECT *
FROM Customers c
WHERE EXISTS (SELECT c.Firstname, c.Lastname
INTERSECT
SELECT #firstname, #lastname)
The logic is: for every row, create a one-row virtual table with the two values, intersect it with the two variables and there must be a result.
For a <> semantic, change EXISTS to NOT EXISTS, rather than changing to EXCEPT, I find the former optimizes better.
All credit to Paul White for this trick.

Why does my SQL query return a record that doesn't match the where clause?

This query returns a result of one record where both the [E-mail] and [E-mail 2] are equal to 'e'. Most definitely the result of a lazy salesman. Any idea why this is the case though?
My query is as shown below so I should only get records where the email is equal to 'emailfromsomeone#hotmail.com' correct?
declare #email as varchar
set #email = 'emailfromsomeone#hotmail.com'
select
C.[No_],
C.[First Name] firstname,
C.[Surname] lastname,
C.[E-Mail] as email,
C.[E-Mail 2] as email_2,
C.[GDPR Opt-in] as GDPR_opt_in,
C.[Salesperson Code] as sales_person
from
[Contact] as C
where
lower(C.[E-Mail]) = lower(#email)
or lower(C.[E-Mail 2]) = lower(#email)
You've declared #email to be a VARCHAR, meaning a single VARCHAR. When you're setting the #email variable, it's being truncated to just the first character.
Try changing VARCHAR to something like VARCHAR(100).
I got it. So i declared the variable like so and then it worked
declare #email VARCHAR(255)
sorry for bothering you stakoverflow!

Replace semicolon with comma and add inverted commas in both end of a string in stored procedure to make it searchable in IN clause

I am very new to SQL query so, sorry If I miss basic details.
Here is the scenario:
I have to search the user email Id inside the column.
the column contains values like
abc#company.com;xyz#company.com;test#company.com;
Now I got the user email id from query:
DECLARE #emailid AS VARCHAR(50)
SELECT #emailid = emailId FROM dbo.tblUser WHERE userName = 'abc' AND projectId ='P1456'
I also replaced the semicolon with a comma like:
COLUMNNAME IN (REPLACE(#emailid,';' ,','))
Now I got the string like abc#company.com,xyz#company.com,test#company.com,
But IN clause treat it as a single string, So how to append inverted commas in each email ids like below to help IN clause to search?
'abc#company.com','xyz#company.com','test#company.com',
Try this:
DECLARE #emailid AS VARCHAR(50)
SELECT #emailid = 'abc#company.com;xyz#company.com;test#company.com;'
SELECT #emailid AS emailid
,REPLACE(SUBSTRING( ''''+#emailid+'''',
PATINDEX(';',#emailid), 51),';',''+ ''''+','+''''+'') AS [replaced]
I hope you are using MSSQL

Add condition only if data exists

I want to add a condition to the WHERE clause ONLY if a variable has data.
I tried with the following case statement, but it has a syntax error.
Declare #last_name varchar(10) = null;
Select * from TABLE1
Where FirstName = 'John'
AND CASE WHEN #last_name IS NOT NULL THEN LastName = #last_name
Select * from TABLE1
where FirstName = 'John'
AND (#last_name IS NULL OR LastName = #last_name)
Others have already posted better ways to write the logic you are trying to express, but just in case you need to use the CASE syntax in the future, remember that the syntax requires you to include the word END. This tells SQL where the expression finishes.
This is what a basic CASE expression would look like:
CASE
WHEN MyField = 'MyValue' THEN 'MyResult'
WHEN MyField = 'MyOtherValue' THEN 'MyOtherResult'
ELSE 'NoResult'
END
Any CASE expression must have at least the CASE, WHEN, THEN, and END. The ELSE isn't strictly necessary - just be aware that if you don't include it, then the expression will return a NULL if none of the WHEN conditions are met.
You can try the following:
Declare #last_name varchar(10) = null;
Select * from TABLE1
Where FirstName = 'John'
AND LastName = ISNULL(#last_name, LastName)
You can also replace ISNULL with COALESCE too.

SQL Update if parameter is not null or empty

I searched some ways to check if a SQL Server parameter is not null or empty but I'm not sure what's the best way to use this when updating several columns:
I had this code at first that was updating without checking for empty or Null values:
UPDATE [Users]
SET FirstName = #firstname, City = #city, Address = #address, ....
WHERE ID = #iduser
Then I added an IF clause before updating, it is working this way but I'm not sure if that's the best way to do it, it is going to be long if I have to update several columns.
--Check if parameter is not null or empty before updating the column
IF (#firstname IS NOT NULL AND #firstname != '')
UPDATE [Users]
SET FirstName = #firstname
WHERE ID = #iduser
IF (#city IS NOT NULL AND #city != '')
UPDATE [Users]
SET City = #city
WHERE ID = #iduser
...
...
If the value is Null or Empty I don't need to update, just keep the original value in the database.
not sure what you are trying to achieve if it is blank, but I would try using IsNull() I don't think there is an IsBlank(), but it shouldn't be too hard to write yourself
Using just IsNull your query would look something like...
Update [Users]
set FirstName = IsNull(#FirstName, FirstName),
City = IsNull(#City, City)
....
Where ...
this will Update the row with the param value if they are NOT null, otherwise update it to itself aka change nothing.
Update [Users]
set FirstName = iif(ISNULL(ltrim(rtrim(#FirstName)), '')='', FirstName, #FirstName),
....
Where ...