Executing query with like is not working - c#

I have this code:
string query = "SELECT * FROM dbo.customer WHERE mobileNumber Like '%#mobileNumber'";
When I execute that code from c#, I got empty results
However when I execute this query in my sql managmenet studio
SELECT * FROM dbo.customer WHERE mobileNumber Like '%454545'
I got result.
What I am missing?

Try this:
string query = "SELECT * FROM dbo.customer WHERE mobileNumber Like '%' + #mobileNumber
This is assuming #mobileNumber is a parameter containing the value for which you want to search.

It seems from your code that #mobileNumber is a parameter. Yet, you place it here as a string.
Try putting the % in a string and the parameter separately unquoted:
string query = "SELECT * FROM dbo.customer WHERE mobileNumber Like '%' + #mobileNumber";

Related

Using multiple like clauses with dapper for paging in a query with SQL Server 2008 R2

I use Dapper to do a paging query in a large table. The function I use is this:
public List<WarehouseLine> GetPagedWarehouseLines(int pageNumber, int rowsPerPage, string criteria) //todo
{
var query = #"SELECT *
FROM
(SELECT
*,
ROW_NUMBER() OVER (ORDER BY ProductDescr) AS RowNum
FROM
WarehouseLine) AS whl
WHERE
whl.RowNum BETWEEN ((#PageNumber - 1) * #RowsPerPage) + 1 AND #RowsPerPage * (#PageNumber)
AND (#Criteria)
ORDER BY ProductDescr";
return _db.Query<WarehouseLine>(query, new { PageNumber = pageNumber, RowsPerPage = rowsPerPage, Criteria = criteria }).ToList();
}
The criteria variable is a string with the following value
(Productdescr like '%%') OR (PartNumber like '%%') OR (SerialNumber like '%%') OR(Manufacturer like '%%') OR (SpecialInstructions like '%%') OR (UDF3 like '%%') OR (producttags like '%%') OR (NotesPerPart like '%%')
Parenthesis aside, the query runs fine in SQL Server Management Studio. But during debugging, I get the following error:
An expression of non-boolean type specified in a context where a condition is expected, near 'ORDER'.
I use the latest stable version of Dapper.
'Criteria' variable is a part of SQL expression, it cannot be treated as SQL parameter.
var query = #"SELECT *
FROM (
SELECT *,
ROW_NUMBER() OVER (ORDER BY ProductDescr) AS RowNum
FROM WarehouseLine) AS whl
WHERE whl.RowNum BETWEEN ((#PageNumber-1)*#RowsPerPage)+1
AND #RowsPerPage*(#PageNumber)
AND "
+ Criteria +
#"ORDER BY ProductDescr";

convert the paramater's date type to varchar , of stored procedure in linq query

I have created this stored procedure to filter products by type, category, country, subsidary, date.
CREATE PROCEDURE [dbo].[FindIncomplete_Products]
#type nvarchar(250),
#category nvarchar(250),
#country nvarchar(250),
#subsidary nvarchar(250),
#date datetime
AS
Begin
select [dbo].[AB_Product].[ProductID],
[dbo].[AB_Product].[ProductTitleEn],
[dbo].[AB_Product].[ProductTitleAr],
[dbo].[AB_Product].[Status],
[dbo].[AB_ProductType].[ProductTypeNameEn],
[dbo].[AB_ProductType].[ProductTypeNameAr],
[dbo].[AB_ProductTypeCategory].[ProductCategoryNameEn],
[dbo].[AB_ProductTypeCategory].[ProductCategoryNameAr],
[dbo].[AB_Subsidary].[SubsidaryNameEn],
[dbo].[AB_Subsidary].[SubsidaryNameAr],
[dbo].[AB_Subsidary].[Country]
from
[dbo].[AB_Product]
inner join
[dbo].[AB_ProductType] on [dbo].[AB_ProductType].[ProductTypeID] = [dbo].[AB_Product].[ProductTypeID]
inner join
[dbo].[AB_ProductTypeCategory] on [dbo].[AB_ProductTypeCategory].[ProductCategoryID] = [dbo].[AB_Product].[ProductCategoryID]
inner join
[dbo].[AB_Subsidary] on [dbo].[AB_Subsidary].[SubsidaryID] = [dbo].[AB_Product].[Subsidary_ID]
WHERE
(#type IS NULL OR [dbo].[AB_Product].[ProductTypeID] LIKE '%' + #type + '%')
AND (#category IS NULL OR [dbo].[AB_Product].[ProductCategoryID] LIKE '%' + #category + '%')
AND (#country IS NULL OR [dbo].[AB_Subsidary].[Country] LIKE '%' + #country + '%')
AND (#subsidary IS NULL OR [dbo].[AB_Product].[Subsidary_ID] LIKE '%' + #subsidary + '%')
AND (#date IS NULL OR [dbo].[AB_Product].[CreatedDate] LIKE '%' + #date + '%')
End
I'm passing the parameter values through LINQ query in my C# controller class. This is that linq query
public ActionResult Program_Search(string type, string category, string country, string subsidary, DateTime? date)
{
var incomplete_product_result = db.Database.SqlQuery<ProductCollection>("FindIncomplete_Products #type = {0}, #category = {1}, #country = {2}, #subsidary = {3}, #date = {4}", type, category, country, subsidary, date).ToList();
return View(incomplete_product_result);
}
Once try to pass parameters by binding with URL like follow
http://localhost:49669/Home/Program_Search?type=002&category=null&subsidary=null&country=null&date=12/12/1889
I'm getting following error
Conversion failed when converting date and/or time from character
string.
Open SSMS (SQL Server Management Studio) and type
EXEC FindIncomplete_Products NULL,NULL,NULL,NULL,'2015-01-01'
and press F5 and you will get that error, without anything to do with the web front end
This issue is this expression:
'%' + #date + '%'
You are concatenating a string to a date so it tries to implicitly cast the string to a date, and it certainly cant convert a % to a date.
To fix it, change this line
AND (#date IS NULL OR [dbo].[AB_Product].[CreatedDate] LIKE '%' + #date + '%')
To this
AND (#date IS NULL OR [dbo].[AB_Product].[CreatedDate] = #date)
in your stored proc
The first line doesn't actually make logical sense. You can't LIKE against a date.
This assumes that there are no further issues in the web code.
How did you create the stored proc if you don't know how to use SSMS?
(This is actually all based on #Bhavek's comment - he noticed it first!)
To fix your "data not coming in view" issue, check the model for incomplete_product_result which is currently not bind to any model object.

Oracle parameters in c# inline query with wildcard

I am having trouble using parameters for my in line oraclae query in c#. Why does the parameter not work within the wildcard?
This line returns no results:
Select id, name from Users where UPPER(name) like '%:name%'
command.Parameters.Add("name", OracleDbType.Varchar2, name.ToUpper(), ParameterDirection.Input);
But this returns:
Select id, name from Users where UPPER(name) like '%" + name.ToUpper() +"%'
Did you mean this?
Select id, name
from Users
where UPPER(name) like '%' ||:name.ToUpper()||'%'
This concatenates your C# variable and the Oracle wildcard characters.

Dynamically sql query to select top (n) elements [duplicate]

This question already has answers here:
How to replace text in string in C#?
(2 answers)
Closed 8 years ago.
SELECT TOP 100 * FROM DSMS_Log.dbo.LoggingDetail WITH(NOLOCK) ORDER BY LogTime DESC
I want to replace find 'TOP 100' string and replace it with 'TOP 200' or any other value.
Can you please let me know how to do it in C#?
if you are writing query in your c# code you can use:
int topCount=1000;
string query= "SELECT TOP ("+i.toString()+") * FROM DSMS_Log.dbo.LoggingDetail WITH(NOLOCK) ORDER BY LogTime DESC"
But if you want to send parameter to your SP then you can use:
Declare #i int=1000;
SELECT TOP (#i) * FROM DSMS_Log.dbo.LoggingDetail WITH(NOLOCK) ORDER BY LogTime DESC
It sounds to me as if you simply want to replace part of the string with another, so like:
string sql = "SELECT TOP 100 * FROM DSMS_Log.dbo.LoggingDetail WITH(NOLOCK) ORDER BY LogTime DESC";
sql = sql.Replace("TOP 100", "TOP 200");
If the number is dynamic and you want to replace it with a different one you could use regex:
string sql = "SELECT TOP 100 * FROM DSMS_Log.dbo.LoggingDetail WITH(NOLOCK) ORDER BY LogTime DESC";
string pattern = #"\bTOP\b *(\d+)";
sql = Regex.Replace(sql, pattern, m => "TOP 200");
DECLARE #topval int=100
SELECT TOP #topval * FROM DSMS_Log.dbo.LoggingDetail WITH(NOLOCK) ORDER BY LogTime DESC
you want to use string replace function.string replace function
If you are not using stored procedures, you can concatenate the limit in the command text in C#:
int toplimit = 200;
cmd.CommandText="SELECT TOP " + toplimit.ToString() + " * FROM DSMS_Log.dbo.LoggingDetail WITH(NOLOCK) ORDER BY LogTime DESC";
I think it should be as simple as this
private string GetSql(int maxRecords)
{
string statement = "SELECT TOP " + maxRecords + " FROM DSMS_Log.dbo.LoggingDetail WITH(NOLOCK) ORDER BY LogTime DESC ";
return statement;
}
you can also modify the parameters and change your SQL query.
I'd use regex for that. Because i think its the best way to get all variations in one statement.
string oldString = "Select top 500 from wherever";
string newLimit = "top 20";
string result = System.Text.RegularExpressions.Regex.Replace(oldString , "TOP (\\d)+",newLimit , System.Text.RegularExpressions.RegexOptions.IgnoreCase );
So put in your old string, replace any "TOP x" string with another version given as newLimit in my Example.
For C# solution you will do better using a parameter instead of string manipulation.
simply like this:
int count = 200;
var sql = string.Format("SELECT TOP {0} FROM [Rest_Of_Your_Query]", count);
if you will use a parameter it will be easier for you to know when to change (in case you want to replace only when the value is 100) and to which value (200, 300 whatever).
For SQL solution take a look at the answer from #Ganesh_Devlekar

How do I execute a MySQL parameterized query in C#?

When I run this command in MySQL:
SELECT * FROM v
WHERE v.firstname LIKE '%a%' OR middlename LIKE '%a%' OR lastname LIKE '%a%'
It returns 4 rows in the result set.
But when I run the same query using parameters in C# it returns only one.
SELECT * FROM v
WHERE v.firstname LIKE ?word OR middlename LIKE ?word OR lastname
cmd.Parameters.AddWithValue("word", '%'+key+'%');
I also tried '%' ?word '%' and adding the parameter (key) only, but this didn't work either.
How do I make this work?
Are you using something like:
cmd.ExecuteScalar()
in your code? It will return only 1 record. Try
cmd.ExecuteReader()
instead.
It looks like you're missing "LIKE ?word" at then end of your second SQL statement.
WHERE v.firstname LIKE ?word OR middlename LIKE ?word OR lastname
are you missing lastname LIKE ?word ?

Categories