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 + '%'
Related
I get this error:
The data types varchar and varchar are incompatible in the modulo operator.
when running this code
' Number LIKE '%' + #search + '%' ';
The number is an integer and this code snippet appears enclosed in ''; due to a dynamic pivot statement. Any ideas how i can run this? thanks
Presumably, you have something like this:
SELECT ' Number LIKE '%' + #search + '%' ';
If so, you have single quotes inside a string. So the "string" is interpreted as:
SELECT (' Number LIKE ') % (' + #search + ') % (' ');
The % is the modulo operator . . . and hence your error.
In order to put single quotes in a string, you need to double them up. Something like this:
SELECT ' Number LIKE ''%'' + #search + ''%'' ';
Are you sure you need those outer quotes, should it not just be
Number LIKE '%' + #search + '%'
Otherwise you'll need to escape the inner quotes. Try this:
'Number LIKE ''%'' + #search + ''%'''
Because % is a modulo operator in SQl Server and it is interpreted as such because to insert quto in a string you need to double it as other answers suggest.
Other solution would be:
'CHARINDEX(' + #search + ', Number) > 0'
I always tend to use that over LIKE oprator with %someString%. Both determine if there is string within the other.
I have a stored procedure that I am passing in a general string variable called #SearchText as a varchar. This variable contains names, either part of a name, or a full name. I need to do a select on a table based on this variable, using wildcards. The inbound variable could be anything like (for the name 'john smith'):
'j', 'joh', 'john', 'sm', 'smith', 'john s', john smith'... you get the point.
So, the blunt approach I took is
select x from TableA
where FirstName like '%' + #SearchText + '%'
OR LastName like '%' + #SearchText + '%'
Obviously when a space is encountered it screws up the result set. Can someone please help me understand how to tweak this so it can match on any "amount" of the full name?
If this has already been answered, I couldn't find it... a hotlink to an existing solution would be just as appreciated here.
I might suggest something like this:
where FirstName + ' ' + Lastname like '%' + replace(#Searchtest, ' ', '%') + '%' or
LastName + ' ' + Firstname like '%' + replace(#Searchtest, ' ', '%') + '%'
However, if you are trying to do such full text searches, you might consider using a full text index. That generally provides the right level of functionality for these types of queries.
You can do this as follows:
select x from TableA
where FirstName+' '+LastName like '%' + #SearchText + '%'
Basically, you concatenate the first and last name first and apply the LIKE operator on the concatenation.
i need query which starts with first name here is my query:
if(#firstName <> '')
BEGIN
set #queryString = #queryString+ ' and UPPER(col_FirstName) like ''%' +#firstName +'%'''
END
if(#lastName <> '')
BEGIN
set #queryString = #queryString + ' and UPPER(col_LastName) like ''%' +#lastName +'%'''
but it is searching first name in middle also i want to search only with initials letters
thanks
Both masks in your constructed condition specify that the search be performed anywhere in the column value:
... + ' and UPPER(col_FirstName) like ''%' + #firstName + '%'''
...
... + ' and UPPER(col_LastName) like ''%' + #lastName + '%'''
The percent sign in the mask stands for "any number of any characters". Placed before the search term, therefore, it would match a value where the search term (#firstName) is preceded by any number of characters. To specify that the col_FirstName value should start with the #firstName value (and possibly have an arbitrary number of characters afterwards), just remove the leading percent, i.e. like this:
... + ' and UPPER(col_FirstName) like ''' + #firstName + '%'''
Insted of these IFs you can do it in one query like so:
...
WHERE ...
AND (#lastName <> '' OR UPPER(col_LastName LIKE '%#lastName%')
AND (#firstName <> '' OR UPPER(col_FirstName LIKE '%#firstName%')
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.
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 .