Select SQL records with blank values - sql-server-2005

I have a stored proc used in SSRS reports which has to return records with blank values for confirmation number field if a blank value is passed or a record with the specified confirmation number if a confirmation number is passed in. It has to return all records if a null value is passed in.
My sql right now is
(IsNull(#ConfirmationNumber,'') = '' or RoomRegistration.ConfirmationNumber
like '%' + #ConfirmationNumber + '%')
my above sql query is returning all results when a blank or null value is passed. How do I modify it to return only the records with blank confirmation number when a blank value is passed and return all values when a null value is passed?
I even tried this variation
(ConfirmationNumber LIKE CASE WHEN #ConfirmationNumber =''
THEN #ConfirmationNumber WHEN #ConfirmationNumber is NULL THEN '%%'
ELSE '%' + #ConfirmationNumber + '%' END )
still doesnt work the way I wanted..Please advise

you where clause should look like so:
#ConfirmationNumber is null
OR RoomRegistration.ConfirmationNumber like '%' + #ConfirmationNumber + '%' )
OR (IsNull(RoomRegistration.ConfirmationNumber, '') = '' AND #ConfirmationNumber = '')
Been awhile though :)

Try this
( ConfirmationNumber LIKE CASE WHEN #ConfirmationNumber =''
THEN #ConfirmationNumber WHEN #ConfirmationNumber is NULL THEN ConfirmationNumber
ELSE '%' + #ConfirmationNumber + '%' END )
When the parameter is null the expression (ConfirmationNumber = ConfirmationNumber) will evaluate which is always true .

Related

Stored procedure with 2 Like parameters

I am looking to use a stored procedure to filter my datagridview by either the user entering the part name into txtPartName or MRPID into txtMRPID. However, this is not filtering as expected and just shows all results from the parts table regardless.
I have a feeling this is due to the way I have implemented the AND or perhaps that I can't perform 2 LIKE statements in one procedure perhaps? Anyway can someone point me in the right direction as how to properly perform this procedure.
CREATE PROCEDURE Parts_ViewAllOrSearch
#PartNameSearch nvarchar(255),
#MRPIDSearch nvarchar(255)
AS
BEGIN
SELECT *
FROM Parts
WHERE #PartNameSearch = ''
OR PartName LIKE '%' + #PartNameSearch + '%'
AND #MRPIDSearch = ''
OR MRP_ID LIKE '%' + #MRPIDSearch + '%'
END
Basically you need parentheses around the OR condition:
SELECT *
FROM Parts
WHERE
(#PartNameSearch = '' OR PartName LIKE '%' + #PartNameSearch + '%')
AND (#MRPIDSearch = '' OR MRP_ID LIKE '%' + #MRPIDSearch + '%')
Why you need that is because AND has higher logical prescedence than OR. So without the parentheses, the WHERE clause is equivalent to:
WHERE
#PartNameSearch = ''
OR (PartName LIKE '%' + #PartNameSearch + '%' AND #MRPIDSearch = '')
OR MRP_ID LIKE '%' + #MRPIDSearch + '%'
... which obviously is not what you want.
Finally, please note that, as it stands, your code just does not seem to really these OR expressions. If a parameter is the empty string, then, once surrounded with wildcards it will match on all possible values (except null values). You would just write this as:
WHERE
PartName LIKE '%' + #PartNameSearch + '%'
AND MRP_ID LIKE '%' + #MRPIDSearch + '%'

Sql using where condition with case and Like

I have a multiple parameter say #route in report builder.I need #route to be able to pass blank (' ') and when that happens everything is displayed on the result, which would be my default for parameter #route. ( as accomplished by
where route LIKE '%' + (LTRIM(RTRIM(#route))) + '%')
Basically do something like this:
SELECT *
FROM #finalTable ft
WHERE CASE WHEN #route = '' THEN route LIKE '%' + (LTRIM(RTRIM(#route))) + '%'
ELSE route IN (#route)
END
To make things more clear:
#route is a string and say has 200 different values. I basically want to set a default value of ' ' (blank or null) and allow say 10 distinct values for the user to select from. So basically if the user does not select anything ( 'cuz the default is blank or could be null )then he/she still gets the whole result set. So if i restrict the user to only pass single values and ' ' being one of them then where #route LIKE '%' + (LTRIM(RTRIM(#route))) + '%' works but I would like it to be done with multiple values being passed as well. I hope it clarifies things more now!!
Any help is appreciated.. thank you in advance
It's not possible to pass a list of parameters directly to an IN statement unfortunately.
If you want to do that, I'd suggest the easiest way is to send a table-valued parameter containing a list of your IDs. That way you can join against it to get the same effect as the IN query you've suggested.
This won't directly permit you to do your conditional WHERE clause, but what you can then do is check whether the table-valued parameter contains any rows at all and act accordingly - perhaps something like:
DECLARE #Routes IDList;
SELECT *
FROM #finalTable ft
LEFT JOIN #Routes r
ON ft.Route=r.Route
CROSS JOIN (SELECT COUNT(*) AS Recs FROM #Routes) cnt
WHERE
1= CASE WHERE cnt.Recs = 0 THEN 1
ELSE CASE WHEN r.Route IS NULL THEN 0 ELSE 1 END
if your #route is something like '1,5,10'
SELECT *
FROM #finalTable ft
WHERE ',' + #route + ',' LIKE '%,' + ft.route + ',%'
I think the normal approach is someting like:
WHERE route = #route OR #route = ''
Often NULL is used for this purpose instead of an empty string:
WHERE route = #route OR #route IS NULL

SQL: building a filter - can this be done without dynamic sql?

This is what i see all the time in a list made by us.
Have to make a filter for 2 columns (i took a shorter example, we have lists with 50 columns, looks the same...)
I was wondering if there's a way to do this somehow different.
What do you guys use to filter records from a table?
/* parameters */
#CostNumber = ...
#Description = ...
/* parameters */
SET #strSQL = '
SELECT [CostLevelId], [CostNumber], [Description]
FROM [CostLevel]
WHERE 1 = 1 ' /* this looks weird, but we'll add the "WHERE" stuff easier */
IF (#CostNumber IS NOT NULL)
BEGIN
SET #strSQL = #strSQL + ' AND [CostNumber] LIKE ''%' + REPLACE(#CostNumber,'''','''''') + '%'' '
END
IF (#Description IS NOT NULL)
BEGIN
SET #strSQL = #strSQL + ' AND [Description] LIKE ''%' + REPLACE(#Description,'''','''''') + '%'' '
END
EXEC (#strSQL)
Why not scrap the dynamic SQL approach?
/* parameters */
#CostNumber = ...
#Description = ...
/* parameters */
SELECT [CostLevelId], [CostNumber], [Description]
FROM [CostLevel]
WHERE [CostNumber] LIKE '%' + #CostNumber + '%'
AND [Description] LIKE '%' + #Description + '%'
Couple things to watch out for - nulls in the #CostNumber and #Description params - you'll have to make sure you convert them to empty strings.
Another thing you'll need to consider is the fact that #Description might contain a % character, and you'll have to escape that for the LIKE to work correctly.
I don't know how to do it when the LIKE operator is involved, when using comparison operators I'm using default values to obtain something like this:
select *
from dbo.SomeTable a
where
(a.IntColumn = #IntColumnValue or #IntColumnValue = -1)
and (a.VarCharColumn = #VarCharValue or #VarCharValue = 'zzz')
This way, if I don't want to apply a particular filter I just set it to the default value (in this example -1 or zzz), so its check always yelds true.
Using the LIKE operator should be something similar, maybe you should set the default value to some sort of string you know will never be found in your data? Something like this?
where (a.VarCharColumn like '%' + #VarCharValue + '%' or #VarCharValue = '§§§TheDefaultValue§§§')
I don't have a way to test this atm, but how about
SELECT [CostLevelId], [CostNumber], [Description]
FROM [CostLevel]
WHERE (#CostNumber IS NOT NULL AND [CostNumber] LIKE ''%' + REPLACE(#CostNumber,'''','''''') + '%'')
OR
(#Description IS NOT NULL AND [Description] LIKE ''%' + REPLACE(#Description,'''','''''') + '%'')
GROUP BY [CostLevelId], [CostNumber], [Description]
Failing that, you could try a UNION instead of OR (and grouping).
You can test to see if the value is null in the query, coupled with your condition and an or statement this allows for optional parameters.
This would work for a like statement.
SELECT [CostLevelId], [CostNumber], [Description]
FROM [CostLevel]
WHERE
(#CostNumber is null or [CostNumber] LIKE '%'+#CostNumber+'%')
and
(#Description is null or [Description] LIKE '%'+#Description+'%')
if its a straight equality comparison you can use coalesce to compare to either the populated variable or, when the variable is null, itself.
SELECT [CostLevelId], [CostNumber], [Description]
FROM [CostLevel]
WHERE
[CostNumber] = coalesce(#CostNumber,[CostNumber])
and
[Description] = coalesce(#Description,[CostNumber])
Keep in mind that this may have an adverse effect on your query plans dependant on which variables are set, table population and database structure etc. You may even find that the dynamic sql approach executes more efficiently than this despite the additional complication in its construction.

Convert search from SQL Server to MySQL

i need to convert this one from SQL Server into MySQL
IF IsNull(#SearchText, '') <> '' BEGIN
SET #SearchText = '%' + #SearchText + '%'
SELECT NewsID,DeptID,DeptName,Title,Details ,NewsDate,img
FROM #tbSearchtextTb
WHERE IsNull(Title,'')+IsNull(Details,'') LIKE #SearchText END
this code will search fro my search word in this columns: Title, Details.
i tried to convert this line but i had lots of errors:
these are my unsuccessful attempts
IF ISNULL(SearchText,'') <> '' THEN
SELECT CatID,CatTitle,CatDescription,CatTitleAr,CatDescriptionAr,PictureID,Published,DisplayOrder,CreatedOn
FROM tmp
WHERE CatTitle + CatDescription + CatTitleAr + CatDescriptionAr
LIKE $SearchText;
and this one
IF $SearchText IS NOT NULL THEN
SELECT CatID,CatTitle,CatDescription,CatTitleAr,CatDescriptionAr,PictureID,Published,DisplayOrder,CreatedOn
FROM tmp
WHERE ISNULL(CatTitle,'') +ISNULL(CatDescription ,'') +ISNULL(CatTitleAr ,'') +ISNULL(CatDescriptionAr,'') LIKE $SearchText;
and many many other ways but i could not find any.
so if you know please let me know, thanks and best regards.
you can use fulltext search in mysql
http://dev.mysql.com/doc/refman/5.5/en/fulltext-search.html
The SQL Server version can also be written:
IF #SearchText <> '' -- null is implicitly <> ''
BEGIN
SELECT NewsID,DeptID,DeptName,Title,Details ,NewsDate,img
FROM #tbSearchtextTb
WHERE IsNull(Title,'')+IsNull(Details,'') LIKE '%' + #SearchText + '%'
END
IsNull is IFNull in MySQL.
Strings are joined using Concat in MySQL
Nulls are implicitly '' in concat
IF SearchText <> '' THEN # << again, this test is sufficient
SELECT
CatID,CatTitle,CatDescription,CatTitleAr,CatDescriptionAr,
PictureID,Published,DisplayOrder,CreatedOn
FROM tmp
WHERE Concat(CatTitle, CatDescription, CatTitleAr, CatDescriptionAr)
LIKE Concat('%',$SearchText,'%');

Issue With Apostrophe

I have a Proc that was coded in Dynamic SQl for one of my Application. It is using to search the Applicants with their last name. Right now it is searching applicants with either their first 2 digits of their last name or full last name. But i have a problem searching Applicants that have Apostrophe in their last name(Example O'Connor). If the client try to search applicant with O' or O'Connor it is throwing an error. They want to search every Applicant with or without Apostrophe in their last name. Please Help I tried everything, but its not working. Below is my search code that using in the Proc to pull applicants:
Add wildcards if necessary
if Rtrim(#FirstName) <> ''
begin
If(Len(#FirstName) < 30) and (CharIndex('%', #FirstName) = 0) and #FirstName != ''
Set #FirstName = char(39) + #FirstName + '%' + char(39)
end
if Rtrim(#LastName) <> ''
begin
If(Len(#LastName) < 60) and (CharIndex('%', #LastName) = 0) and #LastName != ''
Set #LastName = Char(39) + #LastName + '%' + char(39)
end
Now build dinamically the filter base on input parameters
if Rtrim(#LastName) <> ''
select #Where = #Where + ' and a.LastName like '+ Rtrim(#LastName)
You need to escape the apostrophe in the input string (basically replace a single ' with two '') as you build your SQL string
You need to pay attention to this anywhere you choose to pass user input to a SQL server database as its a security issue (SQL Injection Attacks) c.f. Bobby Tables
if Rtrim(#LastName) <> ''
select #Where = #Where + ' and a.LastName like '+ Replace(Rtrim(#LastName),'''','''''') + ''
My suggestion is to write the query to contain an alternate column to be used for filtering with the apostrophe/single quote replaced by any special character such as a #. This allows you to leave the original column intact in case you want to display it.
To do that in SQL Server, you could do something like this:
Select
tbl.strName_Last,
REPLACE(tblOrder.strName_Last, '''','#')) as StrLastNameForFilter
....
Then change your code to filter based on this alternate column, and in the user-provided filter string, replace the apostrophe/single quote with the special character.