Compare String values in SQL - sql-server

I have a stored procedure which is called from a program. This stored procedure is passed 2 names and needs to find similar names in the database. However when I try to compare - 'AFC Bournemouth' with the name in the db which is 'Bournemouth'.
bet.searchFixtureForResult
#homeTeam NVARCHAR(MAX),
#awayTeam NVARCHAR(MAX),
#date DATE
AS
SELECT fixtureId
FROM bet.fixture
WHERE homeTeam IN (SELECT teamId
FROM bet.team
WHERE team LIKE '%' + #homeTeam + '%')
AND awayTeam IN (SELECT teamId
FROM bet.team
WHERE team LIKE '%' + #awayTeam + '%')
AND fixtureDate = #date
This supposedly returns the Id of the fixture that falls within the parameters given. How can compare similar strings such that I compare in the same way you compare with .Contains in C#?

I don't think you need bet.team there at all, your query will be like
SELECT fixtureId
FROM bet.fixture
WHERE (HomeTeam LIKE '%' + #HomeTeam + '%' OR #HomeTeam LIKE '%' + HomeTeam + '%')
AND
(AwayTeam LIKE '%' + #AwayTeam + '%' OR #AwayTeam LIKE '%' + AwayTeam + '%')
AND
fixtureDate = #date;
Here is a little Demo

Related

Search with multiple input and between two date does not work when the date textbox is empty

What I'm trying to do is I'm doing a quicksearch with multiple input so that if either any of the textbox is filled even when there are empty textbox, the data can still be retrieved.
The problem that I've faced is when I've tried to do the searching with date range the data failed to search when the date textbox of the date is empty.
Even when other textbox is not null.
I've also tried finding the date range using this method:
and (convert(varchar, DateIssue, 105) between #DateTo and #DateFrom )
next is query that I used for searching
SELECT * FROM [Table2]
where (ID like '%' + #ID + '%' or ID=#ID )
and(Pic_Mgr like '%' + #Picmgr + '%' or Pic_Mgr=#Picmgr)
and(DEPT like '%' + #dept + '%' or DEPT=#dept)
and ( DateIssue between #DateTo and #DateFrom )
next is the code behind that I used to get the parameter value:
cmd.Parameters.AddWithValue("#ID", txtid.Text)
cmd.Parameters.AddWithValue("#Dept", txtIssDept.Text)
cmd.Parameters.AddWithValue("#Picmgr", txtPICMgr.Text)
cmd.Parameters.AddWithValue("#DateTo", txtdateto.Text)
cmd.Parameters.AddWithValue("#DateFrom", txtdatefrm.Text)
I've tried to do the searching without the date range and it work just fine.So I assume there might be problem with my query regarding handling the datetime data .
Is there any suggestion on how to fix this ??
SELECT * FROM [Table2]
where (ID like '%' + #ID + '%' or ID=#ID )
and(Pic_Mgr like '%' + #Picmgr + '%' or Pic_Mgr=#Picmgr)
and(DEPT like '%' + #dept + '%' or DEPT=#dept)
and (DateIssue between
(case when isnull(#DateTo,'') <>'' then #DateTo else DateIssue end) and
(case when isnull(#DateFrom,'') <>'' then #DateFrom else DateIssue end))

How to skip or ignore where clause when parameter is null or empty

I'm writing a stored procedure about searching the database based on aspx page textbox input text.
This stored procedure works well, but I have a problem.
Sometimes #DeptName and #DutyName parameters are empty or null.
So I want to skip or ignore where clauses when that parameter values are empty. But I am confused as to how to handle this situation.
Please give me your advice.
My stored procedure code:
DECLARE
#CompanyCode varchar(20)
, #DeptName nvarchar(20)
, #DutyName nvarchar(20)
SELECT
#CompanyCode = 'h101'
, #DeptName = 'IT'
, #DutyName = 'Manager'
SELECT
U.ADDisplayName AS UserName
, LOWER(U.UserID) AS EmpID
, ISNULL(CPN.CompanyName, '') AS CompanyCode
, ISNULL(U.DisplayName_Eng, '') AS DisplayName_Eng
, ISNULL(DT.DisplayName, '') AS DeptName
, ISNULL(DTY.DutyName, '') AS DutyName
, ISNULL(U.CellPhone, '') AS CellPhone
, ISNULL(U.ExtensionNumber, '') AS ExtensionNumber
, ISNULL(U.FaxNumber, '') AS FaxNumber
, ISNULL(U.ChargeJob, '') AS ChargeJob
, ISNULL(LOC.LocationName, '') AS LocationName
, ISNULL(U.Workplace, '') AS Workplace
, ISNULL(U.EMail, '') AS EMail
FROM dbo.tb_User U
INNER JOIN dbo.tb_Dept DT
ON U.MainDeptCode = DT.DeptCode
INNER JOIN dbo.tb_Company CPN
ON U.CompanyCode = CPN.CompanyCode
INNER JOIN dbo.tb_Location LOC
ON U.LocationCode = LOC.LocationCode
AND U.CompanyCode = LOC.CompanyCode
AND U.GroupCode = LOC.GroupCode
AND U.DetailCode = loc.DetailCode
INNER JOIN dbo.tb_Duty DTY
ON U.DutyCode = DTY.DutyCode
AND U.CompanyCode = DTY.CompanyCode
AND U.GroupCode = DTY.GroupCode
AND U.DetailCode = DTY.DetailCode
WHERE U.CompanyCode = #companyCode
AND DT.DisplayName like '%' + #DeptName + '%'
AND DTY.DutyName like '%' + #DutyName + '%'
Order by DeptName desc
Thank you.
A very common construction is :
WHERE U.CompanyCode = #companyCode
AND (#DeptName is null or DT.DisplayName like '%' + #DeptName + '%')
AND (#DutyName is null or DTY.DutyName like '%' + #DutyName + '%')
...
...
with (recompile)
The with (recompile) hint at the end of your statement is telling SQL Server to check the optimization plan "after" replacing the variables by their values. Doing so it allows to completely ignore a condition when its parameter is null, resulting normally in an optimal execution (only on very complex statements you will need to do more in order to help the SQL engine to find the better execution plan).
It's also worth noting that using the with (recompile) clause forces to check for a new plan at every execution (instead of reusing an existing one), so if your sentence is going to be executed several times for second, then you will be better suited using an alternative, like parameterized dynamic SQL. Although this is not the most usual situation.
PS: If your parameter can also be an empty string, then use isnull to check both options. You still need to add the recompilation hint to execute it optimally.
WHERE U.CompanyCode = #companyCode
AND (isnull(#DeptName, '') = '' or DT.DisplayName like '%' + #DeptName + '%')
AND (isnull(#DutyName, '') = '' or DTY.DutyName like '%' + #DutyName + '%')
...
...
with (recompile)
Add an extra #DeptName is null and #DeptName ="" to each clause:
WHERE U.CompanyCode = #companyCode
AND ((DT.DisplayName like '%' + #DeptName + '%') or (#DeptName is null) or (#DeptName =''))
AND ((DTY.DutyName like '%' + #DutyName + '%') or (#DeptName is null) or (#DeptName = ''))
Order by DeptName desc
You can try this.
Using ISNULL you can replace NULL with a specified replacement value.
In this case, IF #DeptName is null then replace it with value of DT.DisplayName. same applies to #DutyName.
The Logical Function IIF is used to check empty value but this applies starting SQL2012 version, otherwise CASE expression for SQL2008 or later versions.
WHERE U.CompanyCode = #companyCode
AND DT.DisplayName like '%' + ISNULL(IIF(#DeptName = '',NULL,#DeptName),DT.DisplayName) + '%'
AND DTY.DutyName like '%' + ISNULL(IIF(#DutyName = '',NULL,#DutyName),DTY.DutyName) + '%'
Order by DeptName desc

Do not return all values when SSRS wildcard search is blank

How can a SSRS wildcard search be stopped from returning all values when left blank? Currently, if I enter a value for SKU (generated by the script below) and don't enter at least one value for SKU_Description the report returns all records rather than just the SKU record.
I have parameters set to allow blanks and multiple values because I need the ability to enter either an SKU or an SKU_Description or both, depending on what is know about each product.
WHERE A.sku in (#SKU)
OR B.sku_desc like '%' + #SKU_Description + '%'
I thought something like this might work, but it doesn't:
IIf(Parameters!SKU_Description.Value="", "WHERE A.sku in (#SKU)"
, "WHERE A.sku in (#SKU) or B.sku_desc like '%' + #SKU_Description + '%'")
Every thread I can find is about returning all values when left blank, which is the opposite of what I need to do.
your query might need to look like this instead.
WHERE (#SKU = '' OR A.sku in (#SKU))
AND (#SKU_Description = '' OR B.sku_desc like '%' + #SKU_Description + '%')
if #SKU or #SKU_Description can be NULL then you'll probably want
WHERE (ISNULL(#SKU,'') = '' OR A.sku in (#SKU))
AND (ISNULL(#SKU_Description,'') = '' OR B.sku_desc like '%' + #SKU_Description + '%')
Edit:
you can use this if the Sku and SKU_Description dont have to match for same record.
WHERE A.sku in (#SKU)
OR (#SKU_Description <> '' AND B.sku_desc like '%' + #SKU_Description + '%')

How to pass SQL stored procedure NVARCHAR parameter with Hebrew?

I'm trying to pass an NVARCHAR parameter to my store procedure. The stored procedure is supposed to find all suppliers that match the specified criteria. The only problem I have is that I am trying to pass criteria that contains Hebrew.
ALTER PROCEDURE [dbo].[FindSupplier]
-- Add the parameters for the stored procedure here
#search_criteria nvarchar(100) = ''
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
DECLARE #hebrew as bit = 0
IF #search_criteria LIKE '%[אבגדהוזחטיחכךילמנפףערקשת]%'
BEGIN
SET #hebrew = 1
END
IF #hebrew = 0
BEGIN
SELECT comn020.t_suno 'Supplier Code'
, hebcom020.t_nama 'Supplier Name1'
, hebcom020.t_namb 'Supplier Name2'
FROM com020 WITH (NOLOCK)
INNER JOIN hebcom020 WITH (NOLOCK)
ON hebcom020.t_suno = com020.t_suno
WHERE (LTRIM(RTRIM(com020.t_suno)) LIKE N'%' + #search_criteria + '%')
OR (SOUNDEX(LTRIM(RTRIM(com020.t_suno))) LIKE N'%' + SOUNDEX(#search_criteria) + '%')
OR (LTRIM(RTRIM(hebcom020.t_nama)) LIKE N'%' + #search_criteria + '%')
OR (SOUNDEX(LTRIM(RTRIM(hebcom020.t_nama))) LIKE N'%' + SOUNDEX(#search_criteria) + '%')
OR (LTRIM(RTRIM(hebcom020.t_namb)) LIKE N'%' + #search_criteria + '%')
OR (SOUNDEX(LTRIM(RTRIM(hebcom020.t_namb))) LIKE N'%' + SOUNDEX(#search_criteria) + '%')
END
ELSE /* hebrew */
BEGIN
SELECT com020.t_suno 'Supplier Code'
, hebcom020.t_nama 'Supplier Name1'
, hebcom020.t_namb 'Supplier Name2'
FROM com020 WITH (NOLOCK)
INNER hebcom020 WITH (NOLOCK)
ON hebcom020.t_suno = com020.t_suno
WHERE hebcom020.t_nama Collate Hebrew_CI_AI LIKE N'%' + #search_criteria + '%' Collate Hebrew_CI_AI
OR (LTRIM(RTRIM(hebcom020.t_namb)) LIKE N'%' + #search_criteria + '%')
END
END
When I'm trying to pass something like exec FindSupplier 'ב' the SQL server recognizes char 'ב' as '?'
Your help will be highly appreciated
UPD: exec FindSupplier N'ב' worked
UPD2: In Visual Studio need to run sp with following string
="exec FindSupplier N'" & Parameters!search_criteria.Value & "'"
The problem is simply that the string literal used in the LIKE condition is not prefixed with an N to indicate that it is a Unicode string. The following example shows the difference:
DECLARE #search_criteria NVARCHAR(100) = N'ב';
IF #search_criteria LIKE '%[אבגדהוזחטיחכךילמנפףערקשת]%'
BEGIN
PRINT 'WithOUT "N"-prefix';
END;
IF #search_criteria LIKE N'%[אבגדהוזחטיחכךילמנפףערקשת]%'
BEGIN
PRINT 'WITH "N"-prefix';
END;
Returns:
WITH "N"-prefix
To more easily understand why there is this difference in behavior, consider the following:
-- when the DB has a default collation of Latin1_General_100_CI_AS_SC (code page 1252)
SELECT '%[אבגדהוזחטיחכךילמנפףערקשת]%'
-- %[????????????????????????]%
-- when the DB has a default collation of Hebrew_100_CI_AS_SC (code page 1255)
SELECT '%[אבגדהוזחטיחכךילמנפףערקשת]%'
-- %[אבגדהוזחטיחכךילמנפףערקשת]%
The string literals are parsed in the code page used by the default collation of the current database. If the code page can support these characters, then not prefixing with the upper-case "N" will work. But, if those characters do not exist in that code page, then they are converted into "?"s.

Search Varchar and Integer Columns in T-SQL

I have a search functionality in my application which searches a string value of a particular column. The search text is passed as a parameter to the procedure. Now I have to search in another column which is an integer from another table. The input param is one but now I have to search in both the columns and return the result according to that.
//Query:
#SearchText VARCHAR(8000) = ''
SELECT DISTINCT Id, TransactionId, wfdFieldValue
where (wfdFieldValue LIKE '%' + #SearchText + '%' OR #SearchText = '')
In the above query I have to include the TransactionId in the where condition. So that if the user searched using the TransactionId or the Fieldvalue the query will return the result.
Note: The TransactionId is an Integer DataType.
If I understand you correctly, you'll want a hit in either column to make the row show up in search results. In that case, you'll need a simple OR;
SELECT DISTINCT Id, TransactionId, wfdFieldValue
FROM bop
WHERE #SearchText='' OR
wfdFieldValue LIKE '%' + #SearchText + '%' OR
TransactionId LIKE '%' + #SearchText + '%'
(You can just use LIKE on the integer column right away without manually converting.)
Of note though, this kind of wildcard search with a leading % does not use indexes in an optimal way, performance of this query will most likely not be great as the table grows.
SELECT DISTINCT Id, TransactionId, wfdFieldValue
where wfdFieldValue LIKE '%' + #SearchText + '%'
OR #SearchText = ''
OR CAST(TransactionId AS VARCHAR(50)) LIKE '%' + #SearchText + '%'
A cast should solve it, but I would first think about possible design improvements.

Resources