My inline sql query is like this
DataSet ds = SqlHelper.ExecuteDataset(GlobalSettings.DbDSN, CommandType.Text,
"SELECT TOP 1000 [ID],[Project],[Owner],[Consultant],[Contractor],[Value],
[Level1], [Level2] ,[Status] ,[Category] ,[Country],[CreatedDate],
[CreatedByID], [CreatedByName]
FROM [DBname].[dbo].[tbl_Projects]
where [Category] like %#Category%
and Value=1000
and Country like'%Bahrain%'
order by CreatedDate",
new SqlParameter("#Category","oil") );
everything looks okay to me .But it throws an error
System.Data.SqlClient.SqlException: Incorrect syntax near 'Category'.
I believe it is something I had done wrong when using like query.
Can any one point out what went wrong?
I think this should work
... LIKE '%' + #Category + '%'
cf. T-SQL and the WHERE LIKE %Parameter% clause
Related
I am trying to convert the below into from an Access Database Syntax to sql query syntax using Case-When-Then etc. Can someone help me?
SpreadType: IIf([mv_Loan_Ext1]![LoanPurposeTypeCode] In ("008","080"),"QRLF-" & IIf([FAReceivesPatronage]=0,"NPAT","PAT"),IIf([SecDistrictIndustryCode]="999","Non-QRLF",IIf([PriDistrictIndustryCode]="999","RHL",IIf([mv_Loan_Ext1]![LoanPurposeTypeCode]+0 Between 1 And 7,"Other home",IIf([FANoteIsParticipationPurchased]=1,IIf([mv_FANote]![BranchNbr]="092","100% GP","PP"),IIf([PatronagePoolCode]="14","FCE",IIf([YBSAgStart]<>"No" Or IIf(Trim([AgGrow_NoOperator]) Is Null,0,IIf(Trim([AgGrow_NoOperator])="" Or Trim([AgGrow_NoOperator])="No",0,1))+IIf(Trim([AgNiche]) Is Null,0,IIf(Trim([AgNiche])="" Or Trim([AgNiche])="No",0,1))+IIf(Trim([AgGrowOperator]) Is Null,0,IIf(Trim([AgGrowOperator])="" Or Trim([AgGrowOperator])="No",0,1))>0,"YBS AgStart",IIf([GrainInventoryLoan]="Yes","Grain Inventory",IIf([COVID19] Like "SBA*","PPP",IIf(IIf([FarmTypeAbbr]="",IIf([FCALoanTypeAbbr]="PRIT","FL",IIf([FCALoanTypeAbbr]="REMG","FL","")),[FarmTypeAbbr])<>"FL","General non-farmer","Core farmer loans"))))))))))
You have to rewrite your query like this. You just have too many embed (). This is little mess.
select
case when [mv_Loan_Ext1].[LoanPurposeTypeCode] in ('008', '080') then 'QRLF-' + case FAReceivesPatronage when 0 then 'NPAT' else 'PAT' end
when [SecDistrictIndustryCode] = '999' THEN 'Non-QRLF'
when ...
end
I know that order is not safe, so I want to refactor this code:
#tasks = #search.result.joins(user_application_status: {student_application: [student_profile: :student]})
.order(sort_column + ' ' + sort_direction).page(params[:page])
sort_column is reading from params directly and would be something like user_application_tasks.name and sort_direction would return somethig like asc, I tried refactoring it to:
.order("? ?", sort_column, sort_direction).page(page_params)
but I am getting an error
ActiveRecord::StatementInvalid - PG::SyntaxError: ERROR: syntax error at or near ","
LINE 1: ...HERE (application_statuses.id = 137) ORDER BY ? ?, user_app...
I have done this sort of thing before with where statements like
Thing.where("state = ?" ,params[:state])
Is there some special syntax I am omitting?
EDIT:
The thing I am most worried about is someone being able to inject sql here and do something harmful, as #spickermann mentioned order doesn't sanitize the data so
Thing.order("name; drop table users;")
will result in the users table being destroyed.
order doesn't sanitize attributes when they are provided in a list like where does.
But is accepts as hash like this:
order(sort_column => sort_direction)
See the Rails Guides About Ordering.
I'm doing a school project and need to code a query to filter a dataset to certain variables. All my SQL works fine, except I can't get the LIKE statement to work with %-signs. I believe my syntax is wrong. Can anybody please tell me what I'm doing wrong. Thanks
The code:
qryMovie.SQL.Clear;
qryMovie.SQL.Add('SELECT * FROM Movies');
qryMovie.SQL.Add('WHERE Genre = ' + QuotedStr(genre));
qryMovie.SQL.Add('AND Price BETWEEN ' + minPrice + ' AND ' + maxPrice);
qryMovie.SQL.Add('AND Title LIKE %' + title + '%');
qryMovie.Open;
Error produced:
'Syntax error in query expression 'Genre = 'Action/Adventure'
AND Price BETWEEN 0 AND 200
AND Title LIKE %Star Wars%''
LIKE %Star Wars%
but you need
LIKE '%Star Wars%'
You need to quote % with ':
qryMovie.SQL.Add(' AND Title LIKE ''%' + title + '%''');
Anyway you should use binded parameters instead of concatenating SQL string. It is error-prone and could lead to SQL Injection attacks.
The following code I have written works find. Outputs what I expect.
select distinct
mi_tm.st_event_time,
mi_tm.st_location,
mi_tm.st_log_class,
mi_tm.st_qty,
mi_tm.st_reason,
mi_tm.st_reason_data,
mi_tm.st_sku_code,
mi_tm.st_ulid,
mi_tm.st_user_id,
x_prod.description,
x_supplier.supplier_name
from
mi_tm, x_prod,
x_igd, x_supplier
where
mi_tm.st_date >= {?Start} and
mi_tm.st_date <= {?End} and
mi_tm.st_sku_code = x_prod.prod_code (+) and
mi_tm.st_sku_code = x_igd.prod_code (+) and
x_igd.supplier_no = x_supplier.supplier_no (+) and
mi_tm.st_sku_code like '{?SKU}' and
mi_tm.st_log_class in ('TM_ADJUST_QTY', 'TM_CREATE', 'TM_DELETE')
However for this line
mi_tm.st_sku_code like '{?SKU}' and
I would like it to be able to expect a wildcard parameter, that will return all values run between the dates. Just querying a % seems to crash my report. and I have tried adding '%' around the parameter. But I either get an invalid number error, or SQL not ended properly. I would be grateful for any help on this issue.
Edit: Place this at the bottom
If {?SKU} = '*' then
mi_tm.st_sku_code like '*'
else mi_tm.st_sku_code like '{?SKU}'
I have a query like this. When executing it I am getting this error.
System.Text.StringBuilder qry = new System.Text.StringBuilder();
qry.Append(" SELECT OfferC.TypeIE, OfferC.RegNo ");
qry.Append(" FROM OfferC ");
qry.Append(" WHERE OfferC.RegNo IN (");
qry.Append(string.Join(",",m_SelectableOrganizations.ConvertAll(IntToString).ToArray())).Append(")");
qry.Append(" GROUP BY OfferC.RegNo, OfferC.TypeIE");
qry.Append(" ORDER BY OfferC.Rating;");
You Tried to execute a query that does not include the specified expressions 'OfferC.Rating' as part ot an aggregate function.
I tried to do something like this.
SELECT ...
FROM ...
WHERE ...
GROUP BY ...
ORDER BY ...
But still getting the same error. And a screenshot to error.
Thanks for help.
Include OfferC.Rating in GROUP BY clause, otherwise ORDER BY OfferC.Rating can't happen since it's been grouped with other criteria and not by OfferC.Rating