LINQ query where column contains a specific number >= specific value you want to query - sql

I have a table named SubcodeTable and I want to query in SubsidiaryCode where first 3characters is >= to 21Y
Query in table where a column contains >= '21Y'
SubcodeTable:
Column1 Column2
SubsidiaryCode Desc
18Y-001 AAA
19Y-001 AAA
20Y-001 AAA
21Y-001 CCC
22Y-003 EEE
23Y-001 FF
So output should display:
Column1 Column2
SubsidiaryCode Desc
21Y-001 CCC
22Y-003 EEE
23Y-001 FF
By the way first 3 characters of SubsidiaryCode represent year like 21Y=2021.
I manage to create a SQL query, so how do to it in LINQ query ?
SQL query:
SELECT LEN (Whh_SubsidiaryCode) [StringLength],LEFT(Whh_SubsidiaryCode,2)[FirsttwoCharInSubCode]
,Whd_WHNo [RR NUMBER], Whh_SubsidiaryCode [SubsidiaryCode], Whd_WHSeqNo [SEQ], Whd_WHSplitSeqNo [SPLIT SEQ] ,Whd_WHIssuedQty [QTY],Saw_StockName [ITEM NAME],Saw_StockSpecs1 [ASSET DESCRIPTION]
FROM E_WHDetailEntry
JOIN E_WHHeaderEntry ON Whd_WHNo=Whh_WHNo
JOIN E_StockAndWorkMaster ON Whd_StockCode=Saw_StockCode
WHERE Whd_StockType='FS2'
AND Whh_SubsidiaryCode LIKE '%Y%' AND LEFT(Whh_SubsidiaryCode,2) >= '21'
ORDER BY Whh_SubsidiaryCode
So this is my LINQ query, I tried to use y.Whh_SubsidiaryCode.Substring(0,2) >'20' but it says Too many characters in car literal & operator > cannot be applied to operands of type string and char.
private List<string> GetBudgetCodes()
{
using (var ctx = LinqExtensions.GetDataContext<NXpert.FixedAsset.DataAccess.FixedAssetDataContext>("AccountingDB"))
{
var list = (from x in ctx.DataContext.E_WHDetailEntries
join y in ctx.DataContext.E_WHHeaderEntries
on x.Whd_WHNo equals y.Whh_WHNo
where x.Whd_StockType == "FS2"
&& y.Whh_SubsidiaryCode.Contains("y")
&& y.Whh_SubsidiaryCode.Substring(0,2) >= '21'
select new { y.Whh_SubsidiaryCode }
).DistinctBy(y => y.Whh_SubsidiaryCode).OrderBy(y => y.Whh_SubsidiaryCode).ToList();
var budgetcode = list.Select(y => y.Whh_SubsidiaryCode.Trim()).ToList();
return budgetcode;
}
}

As it says in exception
> cannot be applied to operands of type string and char.
You need to parse Whh_SubsidiaryCode first to be able to compare values.
So this
&& y.Whh_SubsidiaryCode.Substring(0,2) >= '21'
should be like this:
&& Convert.ToInt32(y.Whh_SubsidiaryCode.Substring(0,2)) > 21

y.Whh_SubsidiaryCode.Substring(0,2) >'20' but it says
Too many characters in char literal
Indeed; you can only put one character inside ' in C#. If you want to put more than one character, you need a string, which is delimited by "
Operator > cannot be applied to operands of type string and char
> as a maths operation doesn't work with a string on one side and a char on the other. You can use it on two chars, or on two strings, but not on a mix
'a' > 'b' //false
"a" > "b" //false
"a" > "A" //true - a is ASCII 97, A is ASCII 65. 97 is greater than 65
I'd say you can simply use:
y.Whh_SubsidiaryCode >= "21Y"
if your code is always number number Y, but you should be aware that this is an alphameric comparison. It'll work fine for any other code that is also number number Y. Critically, a string of 100Y is not greater than 21Y because the first character, 1 is not greater than 2
Unless you have other codes like 21X, you can dump the LIKE '%Y%' / Contains("y") - that just slows things down

I finally gotten a solution in SQL.
by using LEN then get the length then using LEFT to get the first 2 char.
Then create a where clause for the condition:
LEFT(Whh_SubsidiaryCode,2) >= '20'
SELECT LEN (Whh_SubsidiaryCode) [StringLength],LEFT(Whh_SubsidiaryCode,2)[FirsttwoCharInSubCode]
,Whd_WHNo [RR NUMBER], Whh_SubsidiaryCode [SubsidiaryCode], Whd_WHSeqNo [SEQ], Whd_WHSplitSeqNo [SPLIT SEQ] ,Whd_WHIssuedQty [QTY],Saw_StockName [ITEM NAME],Saw_StockSpecs1 [ASSET DESCRIPTION]
FROM E_WHDetailEntry
JOIN E_WHHeaderEntry ON Whd_WHNo=Whh_WHNo
JOIN E_StockAndWorkMaster ON Whd_StockCode=Saw_StockCode
WHERE Whd_StockType='FS2'
AND Whh_SubsidiaryCode LIKE '%Y%' AND LEFT(Whh_SubsidiaryCode,2) >= '20'
ORDER BY Whh_SubsidiaryCode
Thanks for the help guys.
About the LINQ I manage to query the results using List, create a function that returns the met condition.
Code:
private static bool CodeFiltered(string code)
{
return ((Convert.ToInt32(code.Substring(0,2)) >= 20));
}
var lstBudgetCodes = GetBudgetCodes();
List<string> ResultCode =new List<string>(lstBudgetCodes.FindAll(CodeFiltered));

Related

Sql query 'IN ' operator is not work error?

I am using CI 'in'operator is not work sql error please check its and share valuable idea...
table
enter image description here
id | coach_name
------------------
9 | GS
------------------
10 | SLR
view and function
$coachID = explode(',',$list['coach']);
$coachname = $this->rail_ceil_model->display_coach_name($coachID);
show result
SLR
need result
GS,SLR
last query result here
SELECT coach_name FROM mcc_coach WHERE id IN('9', '10')
CI code
public function display_coach_name($coachID='')
{
$db2 = $this->load->database('rail',TRUE);
$db2->select('coach_name');
$db2->from('mcc_coach');
$db2->where_in('id',$coachID);
$query = $db2->get();
echo $db2->last_query(); die;
if ($query->num_rows() > 0):
//return $query->row()->coach_name;
else:
return 0;
endif;
}
You must provide an array to in operator so #coachId must be an array not a string
If you are writing this query
SELECT coach_name FROM mcc_coach WHERE id IN('9,10')
it means you are applying in operator on a single id which contains a comma separated value.
So, right query will be
SELECT coach_name FROM mcc_coach WHERE id IN('9','10')

Issue With SQL Pivot Function

I have a SQL query where I am trying to replace null results with zero. My code is producing an error
[1]: ORA-00923: FROM keyword not found where expected
I am using an Oracle Database.
Select service_sub_type_descr,
nvl('Single-occupancy',0) as 'Single-occupancy',
nvl('Multi-occupancy',0) as 'Multi-occupancy'
From
(select s.service_sub_type_descr as service_sub_type_descr, ch.claim_id,nvl(ci.item_paid_amt,0) as item_paid_amt
from table_1 ch, table_" ci, table_3 s, table_4 ppd
where ch.claim_id = ci.claim_id and ci.service_type_id = s.service_type_id
and ci.service_sub_type_id = s.service_sub_type_id and ch.policy_no = ppd.policy_no)
Pivot (
count(distinct claim_id), sum(item_paid_amt) as paid_amount For service_sub_type_descr IN ('Single-occupancy', 'Multi-occupancy')
)
This expression:
nvl('Single-occupancy',0) as 'Single-occupancy',
is using an Oracle bespoke function to say: If the value of the string Single-occupancy' is not null then return the number 0.
That logic doesn't really make sense. The string value is never null. And, the return value is sometimes a string and sometimes a number. This should generate a type-conversion error, because the first value cannot be converted to a number.
I think you intend:
coalesce("Single-occupancy", 0) as "Single-occupancy",
The double quotes are used to quote identifiers, so this refers to the column called Single-occupancy.
All that said, fix your data model. Don't have identifiers that need to be quoted. You might not have control in the source data but you definitely have control within your query:
coalesce("Single-occupancy", 0) as Single_occupancy,
EDIT:
Just write the query using conditional aggregation and proper JOINs:
select s.service_sub_type_descr, ch.claim_id,
sum(case when service_sub_type_descr = 'Single-occupancy' then item_paid_amt else 0 end) as single_occupancy,
sum(case when service_sub_type_descr = 'Multi-occupancy' then item_paid_amt else 0 end) as multi_occupancy
from table_1 ch join
table_" ci
on ch.claim_id = ci.claim_id join
table_3 s
on ci.service_type_id = s.service_type_id join
table_4 ppd
on ch.policy_no = ppd.policy_no
group by s.service_sub_type_descr, ch.claim_id;
Much simpler in my opinion.
for column aliases, you have to use double quotes !
don't use
as 'Single-occupancy'
but :
as "Single-occupancy",

SQL: Can I convert a string value of a "<" operator into an operator in a where clause?

I am storing an operator in a string column for two rows of a table (">", "<=")
I am joining the table with another table and want to make the where clause as dynamic as possible.
I was wondering if it's possible to convert the string value operator into an actual operator for this line of SQL code:
ABS(DATEDIFF(dd,Table2.DUE_DT,GETDATE())) > 120
VS
ABS(DATEDIFF(dd,Table2.DUE_DT,GETDATE())) <= 120
The operator will change depending on matching columns in the row. Is it possible to change the operator based of the string value containing the correct operator? If so, how can this be done?
Below are the two rows from Table1
NEFL_TYPE GRGR_ID NEFL_KEY NEFL_VALUE NEFL_COLUMN
"PDRU" "2600" "PD" "RV" ">"
"PDRU" "2600" "RV" "PD" "<="
This is the snippet of code I use:
INNER JOIN
Table1
ON
Table2.STATUS = Table1.NEFL_KEY
AND
Table1.NEFL_TYPE = 'PDRU'
WHERE
Table1.GRGR_ID = '2600'
AND
ABS(DATEDIFF(dd, Table2.DUE_DT,GETDATE())) > 120
So Table2.STATUS should determine which operator to use in the NEFL_COLUMN
I don't think there's an easy way to do what you want for a general case, not even with dynamic queries or client-side generated queries, as the comparison is per row and performance would be an issue with dynamic queries.
I see 2 ways to solve the particular example case, though:
a) Make 2 separate queries and do a UNION on them
SELECT...
INNER JOIN
Table1
ON
Table2.STATUS = Table1.NEFL_KEY
AND
Table1.NEFL_TYPE = 'PDRU'
WHERE
Table1.GRGR_ID = '2600'
AND
ABS(DATEDIFF(dd, Table2.DUE_DT,GETDATE())) > 120 AND Table1.NEFL_COLUMN = ">"
UNION
SELECT...
INNER JOIN
Table1
ON
Table2.STATUS = Table1.NEFL_KEY
AND
Table1.NEFL_TYPE = 'PDRU'
WHERE
Table1.GRGR_ID = '2600'
AND
ABS(DATEDIFF(dd, Table2.DUE_DT,GETDATE())) <= 120 AND Table1.NEFL_COLUMN = "<="
b) Use 2 range columns instead of an "operator" column
NEFL_TYPE GRGR_ID NEFL_KEY NEFL_VALUE NEFL_COLUMN START END
"PDRU" "2600" "PD" "RV" ">" 121 9999
"PDRU" "2600" "RV" "PD" "<=" 0 120
--------------------------------------------------------------------------
INNER JOIN
Table1
ON
Table2.STATUS = Table1.NEFL_KEY
AND
Table1.NEFL_TYPE = 'PDRU'
WHERE
Table1.GRGR_ID = '2600'
AND
ABS(DATEDIFF(dd, Table2.DUE_DT,GETDATE())) BETWEEN Table1.START AND Table1.END
But none of them are as clean or elegant as I think you would like

Subquery returned more than one value... in sql query, What that means?, and what is wrong?

Why I got this message if the query seems right:
"Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >= or when the subquery is used as an expression.
The statement has been terminated.
" But when I try the query splitted it works fine, I mean, what could happen?
and this is the query :
UPDATE llantas_dictamen_scrap
SET clave_operador =
(SELECT REPLACE(scrap, '-', '') as clave_operador
FROM (SELECT RIGHT(clave_operador, CHARINDEX('-',REVERSE(clave_operador), 1)) as scrap
FROM llantas_dictamen_scrap) t
)
Of course I'm returning more than one one value, What that supposed to mean?
UPDATE llantas_dictamen_scrap
SET clave_operador = RIGHT(clave_operador, CHARINDEX('-',REVERSE(clave_operador), 1) -1)
WHERE CHARINDEX('-',clave_operador, 1) > 0
This one adjusts the position of the call to RIGHT, excluding the '-' we found. There's no need to make a call to REPLACE, because once we know the position of the last trailing '-' , we can just excluding by taking the right-most characters (-1 for its position).
You can't return multiple values for a single row. You are updating multiple rows, yes, for FOR EACH ROW, you are giving clave_operador a single value.
You are setting a single column value equal to more than one column value. If you want to update using the same query your using you have to specify which column you want to use. If you specify to select top 1... with order by that should give you a usable single subquery result for your update statement.
Well if you have
Table A
Col A Col B Col C
1 2 3
1 2 3
And you try
Update Table A Set Col B = (select 5 union select 6)
We won't know if we need to set Column B to 5 or 6, so we get an error.
You need to make sure your sub query only returns one value, one easy way would be to do the following to your subquery (notice the Top 1).
SELECT Top 1 REPLACE(scrap, '-', '')as clave_operador FROM (SELECT RIGHT(clave_operador, CHARINDEX('-',REVERSE(clave_operador),1))as scrap FROM llantas_dictamen_scrap)t
what that means this message java.lang.ClassNotFoundExeption:com.mysql.jdbc.Driver
and this is my code in jform
private void saveActionPerformed(java.awt.event.ActionEvent evt) {
String Number = txt_idinf.getText();
String Name = txt_Name.getText();
String Birthdate = txt_Birthdate.getText();
String Cas = txt_Cas.getText();
String Helth = txt_Helth.getText();
String Sourc = txt_Sourc.getText();
String Children = txt_Children.getText();
String Adresse = txt_Adresse.getText();
String PhoneNumber = txt_PhoneNumber.getText();
String Demande = txt_Demande.getText();
String Procédurs = txt_Procédurs.getText();
Connection conn = null;
PreparedStatement pstm = null;
try{
Class.forName ("com.myql.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://localhost/infocarte","root","root");
pstm = conn.prepareStatement("insert into information values (?,?,?,?,?,?,?,?,?,?,?)");
pstm.setString(1, Number);
pstm.setString(2, Name);
pstm.setString(3, Birthdate);
pstm.setString(4, Cas);
pstm.setString(5, Helth);
pstm.setString(6, Sourc);
pstm.setString(7, Children);
pstm.setString(8, Adresse);
pstm.setString(9, PhoneNumber);
pstm.setString(10, Demande);
pstm.setString(11, Procédurs);
int i = pstm.executeUpdate();
if (i>0){
JOptionPane.showMessageDialog(null, "تم حفظ البيانات");
}
else{
JOptionPane.showMessageDialog(null, "خطأ في حفظ البيانات");
}}
catch(Exception e){
JOptionPane.showMessageDialog(null,e);
}
}

Where is the "LEFT" operator in LINQ?

Using SQL Server 2005 I've run a query like this
SELECT *
FROM mytable
WHERE (LEFT (title, 1) BETWEEN #PREFIXFROM AND #PREFIXTO)
I use this to do alphabet filtering, so for example
PREFIXFROM = a
PREFIXTO = c
and I get all the items in mytable between a and c (inclusive)
How do I do this in linq?
Selecting all the records fine.. but
1) how do I do the "LEFT" operation
and 2) How do I do a <= type operator with a non numeric field?
Any ideas appreciated!
Don't think of the SQL - think of what you're trying to achieve, and how you'd do it in .NET. So you're trying to get the first character, and work out whether it's between 'a' and 'c':
var query = from row in mytable
where row.title[0] >= 'a' && row.title[0] <= 'c'
select row;
or in dot notation:
var query = mytable.Where(row => row.title[0] >= 'a' && row.title[0] <= 'c');
Alternatively:
var query = mytable.Where(row => row.title.Substring(0, 1).CompareTo("a") >= 0 &&
row.title.Substring(0, 1).CompareTo("c") <= 0));