Union causing Firebird 2.5 query to fail - sql

This SQL (Firebird 2.5, Dialect 1) query works fine when I run it in Database Workbench, but it fails when I run it under IBO Console with:
count of column list and variable list do not match.
These two queries run successfully if I run them alone under IBO console, so I'm inferring that the problem is because of the "Union." The number and types of columns match for the two queries--both return string, smallint, string (IBO console regards this as a memo), string--so Union should be valid (and DB Workbench finds it so). Thinking that maybe the length of the data was different, I tried casting the third column as a VarChar(500) but that didn't help. Looking for ideas as to why this doesn't work since the part of our app that is executing the query is apparently choking on this in the same way that IBO Console is.
Select QBI.TXNID as ID,
Cast (1 as SmallInt) as TransactionType,
("Invoice " || QBI.REFNUMBER || ": $" || round(QBI.SUBTOTAL, 2) || " on " || QBI.TXNDATE || " for " || QBI.CUSTOMERREF_FULLNAME) as description,
case
when (QBI.CLASSREF_LISTID = "") then "Invoice has no class in Quickbooks"
else "Invoice class doesn't match any dept on job " || JA.JOBID
end as Problem
from QBINVOICE QBI
Join JOBACCOUNTINGID JA
on QBI.CUSTOMERREF_LISTID = JA.jobaccountingid
and QBI.SOURCEID = JA.SOURCEID
left Join CHARTOFACCOUNTS CA
on (CA.qblistid = QBI.CLASSREF_LISTID and CA.qbsourceID = QBI.SOURCEID)
and CA.CHARTACCOUNTTYPE = "SYSTEM"
and CA.CHARTFETCH = "Y"
left Join DEPARTMENTJOB DJ
on JA.JOBID = DJ.JobID
and DJ.departmentID = CA.DEPARTMENTID
where DJ.DEPARTMENTID is null
and QBI.TXNDATE >= "02/01/2017"
union all
select
QBELD.TXNLINEID as ID,
Cast (2 as SmallInt) as TransactionType,
QBB.VENDORREF_FULLNAME || " bill on " || QBB.TXNDATE || ": $" || round(QBELD.AMOUNT, 2) || " " || QBELD.ACCOUNTREF_FULLNAME || " expense" as description,
case
when (QBELD.CLASSREF_LISTID = "") then "Expense has no class in Quickbooks"
else "Expense class doesn't match any dept on job " || JA.JOBID
end as Problem
from QBTxnExpenseLineDetail QBELD
JOIN QBBILL QBB
on QBELD.TXNLINEID = QBB.TXNID
and QBELD.SOURCEID = QBB.SOURCEID
Join JOBACCOUNTINGID JA
on QBELD.CUSTOMERREF_LISTID = JA.jobaccountingid
and QBELD.SOURCEID = JA.SOURCEID
left Join CHARTOFACCOUNTS CA
on (CA.qblistid = QBELD.CLASSREF_LISTID and CA.qbsourceID = QBELD.SOURCEID)
and CA.CHARTACCOUNTTYPE = "SYSTEM"
and CA.CHARTFETCH = "Y"
left Join DEPARTMENTJOB DJ
on JA.JOBID = DJ.JobID
and DJ.departmentID = CA.DEPARTMENTID
where DJ.DEPARTMENTID is null
and QBB.TXNDATE >= "02/01/2017"

Related

Go over a simple quote in a Where of a SQL query

I have a SQL query where I have to pass a string in my where, my string can have a simple quote in the name of the program and at the same time break the string and create an error in my request.
Yes I would just like to skip the code, but the actual logic has been done so that we are able to modify the code, so I can't just trust that.
Here is the query in my ASP.NET MVC 5 project:
IQueryable<ListeProgrammesCol> query = db.Database.SqlQuery<ListeProgrammesCol>(
"SELECT id AS offreID, nomProgramme AS nom, codeProgramme AS code, dateAjout, dateLastUpdate, gestionEnLigne " +
"FROM tbl_offreCol " +
"WHERE FK_etablissement = " + instId +" AND offreType = 3 AND archive = 0 AND codeProgramme = '" + code + "' AND nomProgramme = '" + progNom + "' " +
"ORDER BY nomProgramme").AsQueryable();
And here is the query if you want to text in SQL Server Management Studio:
SELECT
id AS offreID, nomProgramme AS nom, codeProgramme AS code,
dateAjout, dateLastUpdate, gestionEnLigne
FROM
tbl_offreCol
WHERE
FK_etablissement = 923000
AND offreType = 3
AND archive = 0
AND codeProgramme = '351.A0'
AND nomProgramme = 'RAC en Techniques d'éducation spécialisée'
ORDER BY
nomProgramme
This is the problem: d'éducation
//////UPDATE
I decided to use linq to make my request, so I no longer need to use quotes. Here is the query:
var query = (from oc in db.tbl_offreCol
where oc.FK_etablissement == instId
&& oc.offreType == 3
&& oc.archive == 0
&& oc.codeProgramme == code
&& oc.nomProgramme == progNom
select new ListeProgrammesCol
{
offreID = oc.id,
nom = oc.nomProgramme,
code = oc.codeProgramme,
dateAjout = oc.dateAjout,
dateLastUpdate = oc.dateLastUpdate,
gestionEnLigne = oc.gestionEnLigne
}).OrderBy(x => x.nom).AsQueryable();

Getting {"error":"Null TypeMapping in Sql Tree"} from entity framework core using linq

I have this linq select statment and I am getting this erro {"error":"Null TypeMapping in Sql Tree"} back.
Ill put the code below but is there a way to get more information on what the issue is?
If you need the entities let me know and Ill copy them.
regards
var query = from o in _orderDataDbContext.tblSellFlangeOrders
join od in _orderDataDbContext.tblSellFlangeOrderDetails
on (int?)o.Id equals od.SellFlangeOrderId
join t in _orderDataDbContext.tblTypes
on od.TypeId equals (int?)t.Id
join l in _orderDataDbContext.VLegendeFlangeLengths
on od.LengthId equals (int?)l.Id
join g in _orderDataDbContext.VLegendeGrades
on od.GradeId equals (int?)g.Id
where o.Id == request._flangeOrderID
select new FlangeOrderDetailByPoCodeDto
{
SellFlangeOrderID = o.Id,
DetailID = od.Id,
Price = od.Price1000,
BF = od.Bf,
TypeID = t.Id,
Type = t.Inches1 + "x" + t.Inches2,
LengthID = l.Id,
Length = l.Length + "'" + l.OverLength + "\"",
GradeID = g.Id,
Grade = g.Grade
};
I had a similar issue after upgrading to .net core 3.1 in a code that was working.
The problem, in the end, was something like you have here:
Length = l.Length + "'" + l.OverLength + "\"",
It seems like you cannot concatenate int, decimal, etc... so you have to convert them into a string
Length = l.Length.ToString() + "'" + l.OverLength.ToString() + "\"",

Update using two tables in Ms access vba

I want to update a table using numbers from another table, I want to do the following formla
Y-X(1)-(A1+A2+A3)
X is form table1 while Y,A1,A2,A3 from table2. The new record wil be updated in column X where the ID has only one of the records = 0
Table1
ID || X
-------------
1 || **0**
1 || 155
2 || 4
3 || 0
3 || 0
3 || 234
4 || 0
4 || 0
Table2
ID || Y || A1 || A2 || A3
--------------------------------------
1 || 228 || 1 || 3 || 4
2 || 112 || 6 || 7 || 7
3 || 4 || 22 || 1 || 0
4 || 78 || 76 || 6 || 2
from the above example tables the only column that will match the certiria is ID=1 where only one of them is 0 and the count = 2 so column X
where =0 will be updated ( X2= 228-155-(1+3+4))
Updated table1
ID || X
-------------
1 || **65**
1 || 155
2 || 4
3 || 0
3 || 0
3 || 234
4 || 0
4 || 0
My code is
Private Sub GET_TWO_INJLINE_EST()
DoCmd.SetWarnings False
DoCmd.RunSQL "UPDATE table1 I, table2 P" _
& " SET I.X = IIf(I.X = 0, DLookup(""P.Y-I.X-(P.A1 + P.A2 + P.A3)"" , " _
& " ""table1"", ""[ID]="" & [ID] & "" AND I.X <> 0""), I.X)" _
& " WHERE I.[ID] IN (SELECT I.[ID] FROM table1 I" _
& " GROUP BY I.[ID] HAVING (Count(I.[ID]) = 2)" _
& " AND (Min(I.ID) <> Max(I.X))" _
& " AND (Min(I.X) = 0 OR Max(I.X) = 0))" _
& " AND I.ID=P.ID"
DoCmd.SetWarnings True
End Sub
when I run it show me "Unknown" error.
Consider an UPDATE ... INNER JOIN query and reconciling your DLookUp as you attempt to pass I.X within the string expression. Furthermore, your subquery's Min() <> Max() equality does not compare to same X.
Finally, consider saving the update query as a stored Access query without concatenating in a VBA string which avoids the double quoting and forces you to check syntax error prior to saving. Plus, the database engine caches and pre-compiles for best execution plan.
SQL (save as Access stored query; see DMax inside larger expression)
UPDATE table1 I
INNER JOIN table2 P ON I.ID = P.ID
SET I.X = IIF(I.X=0, (P.Y - DMax("X", "table1", "ID=" & I.ID) - (P.A1+P.A2+P.A3)), I.X)
WHERE I.[ID] IN
(SELECT sub.[ID]
FROM table1 sub
GROUP BY sub.[ID]
HAVING (Count(sub.[ID]) = 2)
AND (Min(sub.X) <> Max(sub.X))
AND (Min(sub.X) = 0 OR Max(sub.X) = 0))
VBA
Private Sub GET_TWO_INJLINE_EST()
DoCmd.SetWarnings True
DoCmd.OpenQuery "mySavedUpdateQuery"
DoCmd.SetWarnings True
End Sub
try changing the second table1 I to table1 J and update all the references to the second table1
UPDATE table1 I, table2 P
Set I.X = IIf(I.X = 0,
DLookup(""P.Y-I.X-(P.A1 + P.A2 + P.A3)"",
""table1"",
""[ID]="" & [ID] & "" AND I.X <> 0""
),
I.X
)
WHERE I.[ID] IN (
SELECT J.[ID] FROM table1 J
GROUP BY J.[ID]
HAVING (Count(J.[ID]) = 2)
AND (Min(J.ID) <> Max(J.X))
AND (Min(J.X) = 0 OR Max(J.X) = 0))
AND J.ID=P.ID

How to add if else or case in SQL select statement

This is my SQL query to fetch data from the tables order and user_master
String str = "select od.total, od.invoice_link, od.status, ";
str += "od.order_type, um.name as sender_name, umr.name as receiver_name, ";
str += "umr.twitter_handle as receiver_twitter_handle, um.twitter_handle as sender_twitter_handle ";
str += "from orders od ";
str += "join user_master um on um.id = od.user_id ";
str += "join user_master umr on umr.id = od.receiver_id ";
str += "where user_id = '"+user_id+"' ";
String json = dao.getResultJSON(str);
return json;
In the database there is this column named order_type which contains values like transfer, request and invoice.I need to return "Payment to" into the variable json if the value in the order_type column is 'transfer' and 'Requested from' if the value in the column is 'request'.Just forget about 'invoice' which i mentioned above.These two will be enough for my expected output..
Anyway thanks in advance
Without knowing where payment_to and requested_from are supposed to come from, here is as shot in the dark:
select
od.total
, od.invoice_link
, od.status
, od.order_type
, um.name as sender_name
, umr.name as receiver_name
, um.twitter_handle as sender_twitter_handle
, umr.twitter_handle as receiver_twitter_handle
, case when od.order_type = 'transfer' then od.payment_to else null end as payment_to
, case when od.order_type = 'request' then od.requested_from else null end as requested_from
from orders od
inner join user_master um on um.id = od.user_id
inner join user_master umr on umr.id = od.receiver_id
where user_id = '"+user_id+"'
In the format you posted:
String str = "select";
str += " od.total";
str += " , od.invoice_link";
str += " , od.status";
str += " , od.order_type";
str += " , um.name as sender_name";
str += " , umr.name as receiver_name";
str += " , um.twitter_handle as sender_twitter_handle ";
str += " , umr.twitter_handle as receiver_twitter_handle";
str += " , case when od.order_type = 'transfer' then od.payment_to else null end as payment_to";
str += " , case when od.order_type = 'request' then od.requested_from else null end as requested_from";
str += " from orders od ";
str += " inner join user_master um on um.id = od.user_id ";
str += " inner join user_master umr on umr.id = od.receiver_id ";
str += " where user_id = '"+user_id+"';";
String json = dao.getResultJSON(str);
return json;
select od.total,
od.invoice_link, od.status,
od.order_type,
um.name as sender_name, umr.name as receiver_name,
umr.twitter_handle as receiver_twitter_handle,
um.twitter_handle as sender_twitter_handle
from orders od
join user_master um on um.id = od.user_id
join user_master umr on umr.id = od.receiver_id
where user_id = SOMETHING
is your SQL query dissected out from what appears to be Java. You should understand that SQL deals in tables; that is, it deals in rectangles full of data. Each result set returns a series of rows. Each row in a result set necessarily must have the same columns as the other rows.
You are asking for two different kinds of rows, one with a Payment to column and the other with a Requested from column. The choice of row depends on some data in the row. This is not going to happen in a single query.
You can do something like this, though.
select
...,
CASE WHEN od.order_type='transfer' THEN receiver_twitter_handle ELSE '' END `Payment to`,
CASE WHEN od.order_type='request' THEN sender_twitter_handle ELSE '' END `Requested from`,
...
This will yield the two columns you want in every row of your result set. One, or both, the columns will contain blanks when irrelevant.
The details of these CASE statements can vary among makes of table server, and you haven't disclosed which one you're using, so there may be a mistake here. But you can fix it.

SQL Server advanced sorting out

I am an asp.net web pages developer I am developing a website in which I need advanced sorting like www.olx.com which is a classifieds website but the problem is that I have more than 25 categories I am using SQL Server & have my tables broken into parts.
Now, as I have many categories so when i sort them for example if I search for samsung but at the same time I want to sort search data by price (high to low or low to high) & also at same time I want to filter data which has a description now I would need to make 100's of queries by using if's but is there a more convenient solution to this problem
Currently I am using this query:
sql = "SELECT * FROM users_table INNER JOIN response_table ON users_table.ID = response_table.ID LEFT OUTER JOIN miscellaneous_table ON users_table.ID = miscellaneous_table.ID LEFT OUTER JOIN response_table2 ON users_table.ID = response_table2.ID";
sql = sql + " where response_table.sub_category='" + incat + "'";
if (Request["search"] != "" && Request["search"] != null)
{
var search = Request["search"].Trim();
string[] querynew = search.Split(' ');
var searchquery = " and ";
foreach (string word in querynew)
{
searchquery += " users_table.adtitle LIKE '%" + word + "%' OR ";
}
sql = sql + searchquery.Remove(searchquery.Length - 4);
}
if (Request["min"] != "" && Request["min"] != null && Request["max"] != null && Request["max"] != "")
{
sql = sql + " and (CAST(response_table.price AS Float)) between " + Request["min"].Trim() + " AND " + Request["max"].Trim();
}
Thanks
You can use this short hand in the WHERE clause
Assuming your filter are #col1, #col2, #col3
SELECT ...
FROM ...
WHERE (#col1 = 0 OR col1 = #col1)
AND (#col2 = '' OR col2 = #col2)
AND (#col3 = 0 OR col3 = #col3)
So with the above where clause, if the user only supply filter for col2 then just pass 0 in for col1 & col2 and it will unfilter these.