Two Optional parameters on one column in stored procedure - sql

I have table eRx (store electronic prescription) which has a pharmacy column. I am passing two optional parameters for pharmacy.
I declared the parameters like this:
DECLARE #pharmacy varchar(50) = null,
#Pharmacy1 varchar(50) = null
and use them in the where clause
WHERE (eRx.Pharmacy LIKE '%' + #Pharmacy + '%'
OR #Pharmacy IS NULL
OR eRx.Pharmacy LIKE '%' + #Pharmacy1 + '%'
OR #Pharmacy1 IS NULL)
If I am passing only one parameter, I am getting all records. It is not working as expected.
For example, if I will pass #pharmacy = 'CVS', I am getting all the rows. If I will pass both the parameter, then result is returned as expected.
Please help me

You want to find records that match both conditions:
match #Pharmacy when given AND
match #Pharmacy1 when given
You have OR instead. You are saying: select the row when #Pharmacy matches or #Pharmacy is null or ... So when #Pharmacy is null the whole condition is matched.
You want
WHERE (eRx.Pharmacy LIKE '%' + #Pharmacy + '%' OR #Pharmacy IS NULL)
AND (eRx.Pharmacy LIKE '%' + #Pharmacy1 + '%' OR #Pharmacy1 IS NULL)

I think the logic you want is that all rows are returned only when both values are NULL. Otherwise rows matching either values are returned.
If so, you can be explicit like this:
WHERE eRx.Pharmacy LIKE ('%' + #Pharmacy + '%') OR
eRx.Pharmacy LIKE ('%' + #Pharmacy1 + '%') OR
(#Pharmacy IS NULL AND #Pharmacy1 IS NULL)
Note that + returns NULL if any arguments are NULL. This works because with NULL values the first two conditions return NULL which is equivalent to FALSE in this context.

Related

Compare variable against multiple columns of different data types?

I am trying to lookup a search term passed into #Search in both an INT column and a NVARCHAR column.
I have done searching multiple columns in the past similar to below but have never had to compare against different column types.
#Search NVARCHAR(1000)
SELECT
[Stuff]
FROM
[Tables]
WHERE
[IDColumn] = ISNULL(#Search, [IDColumn])
OR
[TextColumn] LIKE '%' + TRIM(#Search) + '%'
How can the passed in variable be checked against multiple columns of different data types?
You need to convert the values. If it is a character, I would suggest try_convert():
WHERE IDColumn = TRY_CONVERT(INT, #Search) OR
TextColumn LIKE CONCAT('%', TRIM(#Search), '%')

WHERE clause with OR operator not giving intended result

I want to write a stored procedure for a search function. I have a database of movies and I should be able to search a movie by Movie.Name, Movie.Producer, Movie.Director and appearing Cast.Name.
CREATE PROCEDURE RetrieveSearchResults
#tokenParam VarChar
AS
Select *
from
(Movie
join
Cast on Movie.MovieID = Cast.MovieID)
join
Actor on Actor.ActorID = Cast.ActorID
where
(Movie.Name like '%' + #tokenParam + '%')
or (Movie.Producer like '%' + #tokenParam + '%')
or (Movie.Director like '%' + #tokenParam + '%')
or (Actor.Name like '%' + #tokenParam + '%')
Upon execution
RetrieveSearchResults 'Almighty'
I get almost all tuples with no similar literal as 'Almighty'
Am I missing something?
Try declaring the varchar limit. VARCHAR(100) or something like that. It may be making assumptions on the length and cutting it down to a VARCHAR(1) or similar. The problem with declaring VARCHAR without a length is the system will assign for you and it may not be what you expect.

Build dynamic query according to variable value

I am using SQL Server 2008 R2.
I am facing problem while fetching records from database in Role Based Access.
I have a Table let us say TableA. I have 5 Columns in it i.e, ID (primary key), FirstName, LastName, RegistrationNumber, EmployeeIdent.
All the columns except ID are of Varchar type.
I have a stored procedure to search the records. I am passing string to it and finding matching records from all five columns.
Now, the problem I am facing is in Role Based Access.
The requirement is when user is of "Admin" type then find matching records from all five columns but when is of "naive" user type then search matching records from only ID column.
I have passed the variable #userType to stored procedure from which I can determine the user type.
One way to resolve this problem is If Condition. Like if (#userType) = 'Admin' then some query Else Some other.
But I don't want to write query in If Condition.
Another way to resolve this is to store query in varchar type of variable and then execute is using EXEC (), but I have heard that it creates more overhead on server (I am not sure about it).
So any other way to fulfill this requirement?
The query to search records is
DECLARE #SearchText VARCHAR(MAX)= ''
SELECT *
FROM TableA
WHERE
Convert(varchar,ID) LIKE CASE WHEN LEN(#SearchText) = 0 THEN Convert(varchar,ID) ELSE '%'+ ISNULL(#SearchText,'0') + '%' END OR
FirstName LIKE CASE WHEN LEN(#SearchText) = 0 THEN FirstName ELSE '%'+ ISNULL(#SearchText,'') + '%' END OR
LastName LIKE CASE WHEN LEN(#SearchText) = 0 THEN LastName ELSE '%'+ ISNULL(#SearchText,'') + '%' END OR
RegistrationNumber LIKE CASE WHEN LEN(#SearchText) = 0 THEN RegistrationNumber ELSE '%'+ ISNULL(#SearchText,'') + '%' END OR
EmployeeIdent LIKE CASE WHEN LEN(#SearchText) = 0 THEN EmployeeIdent ELSE '%'+ ISNULL(#SearchText,'') + '%' END
SELECT
*
FROM TABLEA
WHERE
(#userType = 'admin'
--add any other criteria for admin type here
) or (
#userType = 'naive'
--add any other criteria for naive type here
)

struggling with creating Insert query

I create Insert statement for organization table like this:
select'Insert into Organizations(Name,ContactPerson,ContactNumber,Mobilenumber)values('''+Nameofthecompany+''+','+Nameofthepersonresponsibleforrecruitment+','+PhoneNumber+','+MobileNumber+''')' from Organization
When I execute this statement I get insert statement. But the issue is where the value is null, it shows all columns null.
Example: (in database)
Name: xxxx
ContactPerson: zzzz
ContactNumber:444444
MobileNumber: null
so my insert statement looks like:
Null.
I want only that column provide null. other details showing properly. Is there any way in sql server? Help me anyone...
The result of concatenating anything to NULL, even itself, is always NULL. Workaround with ISNULL function:
select'Insert into Organizations(Name,ContactPerson,ContactNumber,Mobilenumber)
values('''+ISNULL(Nameofthecompany, 'NULL')+''+','
+ISNULL(Nameofthepersonresponsibleforrecruitment, 'NULL')+','
+ISNULL(PhoneNumber, 'NULL')+','
+ISNULL(MobileNumber, 'NULL')+''')'
from Organization
Demo on SQLFiddle
Sure - just use ISNULL(..) to turn a NULL into e.g. an empty string:
SELECT
'INSERT INTO Organizations(Name, ContactPerson, ContactNumber, Mobilenumber) VALUES(''' +
ISNULL(Nameofthecompany, '') + '' + ',' +
ISNULL(Nameofthepersonresponsibleforrecruitment, '') + ',' +
ISNULL(PhoneNumber, '') + ',' + ISNULL(MobileNumber,'') + ''')'
FROM Organization
When you are adding each of the parameters to the SQL statement, you need to check whether they're null, and if so use the keyword NULL, otherwise include a literal string surrounded with single quotes, but bearing in mind that if the string contains any single quotes, they need to be replaced with two single quotes.
Update the SQL for each parameter something like the following:
CASE WHEN MobileNumber IS NULL THEN 'NULL' ELSE '''' + REPLACE(MobileNumber, '''', '''''') + '''' END

SQL Search Query With Null and ''

I have a query that I'm building for an application. The database is setup in SQL Server 2008. I want to use a query similar to below, however, I will be using this 'Where' clause for about 4 other columns using the same requirements. Is this the appropriate way to test for null or '' in a column that is VarChar(255) and does allow nulls.
Ideally, if the variable #UutSerialNumber is null or empty (''), I want all the results, but if it is not, I want to use the 'LIKE' clause. Is this the proper way of doing this and will it work? It seems to work until I start adding more columns to the Where clause.
Also, how would I handle a "text" datatype using the same type of query?
SELECT DeviceName, UutStatus
FROM MyTable
WHERE (UutSerialNumber LIKE '%' + #UutSerialNumber + '%' OR UutSerialNumber LIKE '%%' AND (#UutSerialNumber = '' OR #UutSerialNumber IS NULL)) AND ...
Help is appreciated. Thanks everyone!
It amy seem like duplication of SQL but the best way to do this is in terms of performace is using IF ... ELSE
IF ISNULL(#UutSerialNumber, '') = ''
BEGIN
SELECT DeviceName, UutStatus
FROM MyTable
-- MORE EXPRESSIONS
END
ELSE
BEGIN
SELECT DeviceName, UutStatus
FROM MyTable
WHERE (UutSerialNumber LIKE '%' + #UutSerialNumber + '%'
-- MORE EXPRESSIONS
END
It can be done within the WHERE clause if you are doing it on multiple columns and the query you posted wasn't far off it was just missing additional parenthesis along with having a redundant clause.
SELECT DeviceName, UutStatus
FROM MyTable
WHERE (ISNULL(#UutSerialNumber, '') = '' OR UutSerialNumber LIKE '%' + #UutSerialNumber + '%')
AND (ISNULL(#AnotherParameter, '') = '' OR AnotherColumn LIKE '%' + #AnotherParameter + '%')
Convert the text type to VARCHAR(MAX).
as a footnote, I personally would use the CHARINDEX rather than concatenating strings in the like:
WHERE (ISNULL(#UutSerialNumber, '') = '' OR CHARINDEX(#UutSerialNumber, UutSerialNumber) > 0)
This is nothing more than a footnote however as I have done no performance testing, I just think it is easier on the eye!
SELECT DeviceName, UutStatus
FROM MyTable
WHERE ((#UutSerialNumber = '') OR (#UutSerialNumber is null)) OR (UutSerialNumber like #UutSerialNumber)
add '%' to the last #UutSerialNumber if you think you need