I'm developing in MVC2 using VB.NET and MySQL and ran into a problem trying to convert a simple SQL query to LINQ.
SQL Query:
SELECT Location_Number, sum(Column1) as totalC1, sum(Column2) as totalC2
FROM MyTable
WHERE year = 2010 and month = 8
GROUP BY Location_Number
ORDER BY Location_Number
LINQ Query:
From r In MyTable _
Where r.Year = 2010 And r.Month = 8 _
Group r By LN = r.Location_Number Into l = Group _
Order By LN _
Select New With { _
.Location_Number = LN, _
.DepositCount = l.Sum(Function(r) r.Column1), _
.OtherCount = l.Sum(Function(r) r.Column2) _
}
The error generated is:
An error occurred while executing the command definition. See the inner exception for details.
The inner exception is:
Unknown column 'GroupBy1.K1' in 'field list'
Here is the SQL generated by LINQ:
SELECT `Project1`.`Location_Number`, `Project1`.`C1`, `Project1`.`C2`
FROM (
SELECT `GroupBy1`.`A1` AS `C1`, `GroupBy1`.`A2` AS `C2`, `GroupBy1`.`K1` AS `Location_Number`
FROM (
SELECT Sum(`Column1`) AS `A1`, Sum(`Column2`) AS `A2`
FROM `MyTable` AS `Extent1`
WHERE (`Extent1`.`Year` = #p__linq__0) AND (`Extent1`.`Month` = #p__linq__1)
GROUP BY `Extent1`.`Location_Number`
) AS `GroupBy1`
) AS `Project1`
ORDER BY `Location_Number` ASC
Looking at that query its easy to spot whats causing the error. Simply, the most inner query only returns 2 columns, while the query right above it is trying to SELECT 3, thus the Unknown Column Error. So why is this happening? What is wrong with my LINQ query?
Thank you
It is a MySQL connector bug: http://bugs.mysql.com/bug.php?id=46742
Is not fixed in last (6.3.5) version.
Good news! That bug was fixed on 6.3.7 (see comments in http://bugs.mysql.com/bug.php?id=46742).
Yes, it's a mySQL connector bug.
Try this:
Using context = New YourContext()
Dim sql = "SELECT Location_Number, sum(Column1) as totalC1, sum(Column2) as totalC2 FROM MyTable WHERE year = #YEAR and month = #MONTH GROUP BY Location_Number ORDER BY Location_Number"
Dim args = New DbParameter()
{
New SqlParameter() With {Key .ParameterName = "YEAR", Key .Value = 2010}, New SqlParameter() With {Key .ParameterName = "MONTH", Key .Value = 8}
}
Return context.ExecuteStoreQuery(Of MyTable)(sql, args).ToList()
End Using
Related
I have multiple models in Sparx Enterprise Architect in file-based, i.e. using MS access.
I'm using a custom template to populate a table with data from object's properties, including some with <memo> fields.
This is the query i'm using in the template fragment:
SELECT obj.object_id,
obj.Stereotype,
objp.Property as Prop,
switch(objp.Value = '<memo>', objp.Notes, objp.Value LIKE '{*}',
NULL, 1=1, objp.Value) AS Val,
(SELECT tobj2.ea_guid & tobj2.Name FROM t_object tobj2 WHERE
tobj2.ea_guid = objp.Value) AS [Obj-Hyperlink]
FROM t_object obj
INNER JOIN t_objectproperties objp
ON (obj.object_id = objp.object_id)
WHERE obj.object_id = #OBJECTID# AND obj.Stereotype='Data-
Stream' AND objp.Property NOT IN ('isEncapsulated')
ORDER BY objp.Property ASC;
I found that the when these fields are longer than 249 chars I get an error message when generating the reports and the cell in the generated table is simply empty. This is also noticeable with a query:
The error I'm getting states:
"Error Processing xml document: an invalid character was found in text context"
Is there any workarround to enable including the <memo> fields' data with more than 249 chars in the reports?
Any help is much appreciated.
I've found a workaround for this by joining two queries with a "Union all". The first query will handle the non-memo fields with the switch function and the second one the memo fields without the switch function.
select
obj.object_id,
obj.Stereotype,
objp.Property as Prop,
objp.Notes AS Val,
(
SELECT
tobj2.ea_guid & tobj2.Name
FROM
t_object tobj2
WHERE
tobj2.ea_guid = objp.Value
) AS [Obj-Hyperlink]
from
t_objectproperties objp
left join t_object obj on (obj.object_id = objp.object_ID)
where
obj.object_id = #OBJECTID#
AND obj.Stereotype = 'Data-Stream'
AND objp.Property NOT IN ('isEncapsulated')
AND objp.Value = "<memo>"
UNION ALL
SELECT
obj2.object_id,
obj2.Stereotype,
objp2.Property as Prop,
switch(
objp2.Value LIKE '{*}', NULL, 1 = 1, objp2.Value
) AS Val,
(
SELECT
tobj2.ea_guid & tobj2.Name
FROM
t_object tobj2
WHERE
tobj2.ea_guid = objp2.Value
) AS [Obj-Hyperlink]
FROM
t_object obj2
INNER JOIN t_objectproperties objp2 ON (obj2.object_id = objp2.object_id)
WHERE
obj2.object_id = #OBJECTID#
AND obj2.Stereotype = 'Data-Stream'
AND objp2.Property NOT IN ('isEncapsulated')
and objp2.Value <> "<memo>"
order by
3 asc;
Thanks a lot #geertbellekens for your comment which was crucial to find this solution.
When my SQL query has a count function in the query it does not want to display the data in the DBGRID and I'm getting a "MySqlException was unhandled" error. As soon as I remove the count function it runs smoothly and displays the data on the DB grid.
Code below:
Dim connection As New MySqlConnection("Server info")
Dim cmd As New MySqlCommand("SELECT COUNT(a.client_id), a.CLIENT_ID,b.c_name, b.C_surname FROM tblinv_info a JOIN tblclientinfo b ON a.CLIENT_ID = b.CLIENT_ID WHERE extract(year from a.inv_date) in ('2018','2019') AND a.Client_id = b.Client_id GROUP BY a.client_id ORDER BY count(a.client_id) desc LIMIT 10", connection)
cmd.CommandTimeout = 500
Dim adapter As New MySqlDataAdapter(cmd)
Dim table As New DataTable()
adapter.Fill(table)
dbreport.DataSource = table
Any idea on why this could be happening? I'm running the program in Visual Studio coding with VB.NET and using a MySql database. The SQL command runs fine on the localhost database.
Error: Error code is as follows: An unhandled exception of type 'MySql.Data.MySqlClient.MySqlException' occurred in MySql.Data.dll
Additional information: Fatal error encountered attempting to read the resultset.
I hope you are well.
I think, the problem is, in the Select query, all the fields have a name column, but the counter, don't.
SELECT COUNT(a.client_id), a.CLIENT_ID,b.c_name, b.C_surname ...
And, the filler and data source don't know where to place the counter column.
Set As name to counter column.
SELECT COUNT(a.client_id) AS Counter1, a.CLIENT_ID,b.c_name, b.C_surname
adapter.Fill(table)
dbreport.DataSource = table
You have missing your fields in group by
Run this in SQL query editor
SELECT COUNT(a.client_id) as cnt, a.CLIENT_ID, b.c_name, b.C_surname -- NOTE CHANGE
FROM
tblinv_info a JOIN
tblclientinfo b ON a.CLIENT_ID = b.CLIENT_ID
WHERE
extract(year from a.inv_date) in ('2018','2019') AND
a.Client_id = b.Client_id
GROUP BY
a.client_id,
b.c_name, -- NOTE CHANGE
b.C_surname -- NOTE CHANGE
ORDER BY
cnt desc -- NOTE CHANGE
LIMIT 10
It sounds like your query timed out during execution.
You can increase command timeout using CommandTimeout.
cmd.CommandTimeout = 120; // 2 minutes (example)
Detailed code:
Dim connection As New MySqlConnection("My Server info")
Dim cmd As New MySqlCommand("SELECT COUNT(a.client_id), a.CLIENT_ID,b.c_name, b.C_surname FROM tblinv_info a JOIN tblclientinfo b ON a.CLIENT_ID = b.CLIENT_ID WHERE extract(year from a.inv_date) in ('2018','2019') AND a.Client_id = b.Client_id GROUP BY a.client_id ORDER BY count(a.client_id) desc LIMIT 10", connection)
cmd.CommandTimeout = 120
Dim adapter As New MySqlDataAdapter(cmd)
Dim table As New DataTable()
adapter.Fill(table)
dbreport.DataSource = table
Ok I finally got the problem sorted.
The mysql.data.dll file I was using as a reference (ver6.3.5.0) was too old.
I downloaded version 6.4.4.0 and removed the old reference and now it displaying perfectly.
I am developing a sequence in MySQL & VB.NET in which, when deleting a record, the number that identifies it, is deleted and put a sequence of 1 to 'n', the sequence is as follows.
this is the instruccion for MySQL.
SET #rownum=0;
UPDATE id_line t, (SELECT #rownum:=#rownum+1 rownum, id_line.* FROM id_line WHERE id_line.line_name=59999 and id_line.line_no<>0) r
SET t.line_no = r.rownum
WHERE (t.id_line_b = r.id_line_b)
in VB.net I use this
cmdB = New MySqlCommand("SET #rownum=0 UPDATE id_line t, (SELECT #rownum=:#rownum+1 rownum, id_line.* FROM id_line WHERE id_line.line_name='" & TextBox1.Text & "' and id_line.line_no<>0) r ) SET t.line_no = r.rownum WHERE(t.id_line_b = r.id_line_b)", conn)
but VB sends this error
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'UPDATE id_line t, (SELECT #rownum=:#rownum+1 rownum, id_line.* FROM id_lin' at line 1
Could you help me please in this error?
Updated 1:
This is my string connection.
Public conString As String = "Data Source=server_one;port=3306;Initial Catalog=test_db;User Id=root;password=root;Allow User Variables=True"
other better way for
create mysql procedure for delete mysql data query
https://www.tutorialspoint.com/What-is-stored-procedure-and-how-can-we-create-MySQL-stored-procedures
I found the error, a parenthesis, it was misplaced, this is the correct code.
cmdB = New MySqlCommand("SET #rownum:=0; UPDATE id_line t, (SELECT #rownum:=#rownum+1 rownum, id_line.* FROM id_line WHERE id_line.line_name='" & TextBox1.Text & "' and id_line.line_no<>0) r SET t.line_no = r.rownum WHERE(t.id_line_b = r.id_line_b)", conn)
Thank you everyone for your attention and support.
Regards.
Presently troubleshooting a problem where running this SQL query:
UPDATE tblBenchmarkData
SET OriginalValue = DataValue, OriginalUnitID = DataUnitID,
DataValue = CAST(DataValue AS float) * 1.335
WHERE
FieldDataSetID = '6956beeb-a1e7-47f2-96db-0044746ad6d5'
AND ZEGCodeID IN
(SELECT ZEGCodeID FROM tblZEGCode
WHERE(ZEGCode = 'C004') OR
(LEFT(ZEGParentCode, 4) = 'C004'))
Results in the following error:
Msg 8114, Level 16, State 5, Line 1
Error converting data type nvarchar to float.
The really odd thing is, if I change the UPDATE to SELECT to inspect the values that are retrieved are numerical values:
SELECT DataValue
FROM tblBenchmarkData
WHERE FieldDataSetID = '6956beeb-a1e7-47f2-96db-0044746ad6d5'
AND ZEGCodeID IN
(SELECT ZEGCodeID
FROM tblZEGCode WHERE(ZEGCode = 'C004') OR
(LEFT(ZEGParentCode, 4) = 'C004'))
Here are the results:
DataValue
2285260
1205310
Would like to use TRY_PARSE or something like that; however, we are running on SQL Server 2008 rather than SQL Server 2012. Does anyone have any suggestions? TIA.
It would be helpful to see the schema definition of tblBenchmarkData, but you could try using ISNUMERIC in your query. Something like:
SET DataValue = CASE WHEN ISNUMERIC(DataValue)=1 THEN CAST(DataValue AS float) * 1.335
ELSE 0 END
Order of execution not always matches one's expectations.
If you set a where clause, it generally does not mean the calculations in the select list will only be applied to the rows that match that where. SQL Server may easily decide to do a bulk calculation and then filter out unwanted rows.
That said, you can easily write try_parse yourself:
create function dbo.try_parse(#v nvarchar(30))
returns float
with schemabinding, returns null on null input
as
begin
if isnumeric(#v) = 1
return cast(#v as float);
return null;
end;
So starting with your update query that's giving an error (please forgive me for rewriting it for my own clarity):
UPDATE B
SET
OriginalValue = DataValue,
OriginalUnitID = DataUnitID,
DataValue = CAST(DataValue AS float) * 1.335
FROM
dbo.tblBenchmarkData B
INNER JOIN dbo.tblZEGCode Z
ON B.ZEGCodeID = Z.ZEGCodeID
WHERE
B.FieldDataSetID = '6956beeb-a1e7-47f2-96db-0044746ad6d5'
AND (
Z.ZEGCode = 'C004' OR
Z.ZEGParentCode LIKE 'C004%'
)
I think you'll find that a SELECT statement with exactly the same expressions will give the same error:
SELECT
OriginalValue,
DataValue NewOriginalValue,
OriginalUnitID,
DataUnitID OriginalUnitID,
DataValue,
CAST(DataValue AS float) * 1.335 NewDataValue
FROM
dbo.tblBenchmarkData B
INNER JOIN dbo.tblZEGCode Z
ON B.ZEGCodeID = Z.ZEGCodeID
WHERE
B.FieldDataSetID = '6956beeb-a1e7-47f2-96db-0044746ad6d5'
AND (
Z.ZEGCode = 'C004' OR
Z.ZEGParentCode LIKE 'C004%'
)
This should show you the rows that can't convert:
SELECT
B.*
FROM
dbo.tblBenchmarkData B
INNER JOIN dbo.tblZEGCode Z
ON B.ZEGCodeID = Z.ZEGCodeID
WHERE
B.FieldDataSetID = '6956beeb-a1e7-47f2-96db-0044746ad6d5'
AND (
Z.ZEGCode = 'C004' OR
Z.ZEGParentCode LIKE 'C004%'
)
AND IsNumeric(DataValue) = 0
-- AND IsNumeric(DataValue + 'E0') = 0 -- try this if the prior doesn't work
The trick in the last commented line is to tack on things to the string to force only valid numbers to be numeric. For example, if you wanted only integers, IsNumeric(DataValue + '.0E0') = 0 would show you those that aren't.
I'm trying to translate a sql query into LINQ to SQL. I keep getting an error "sequence operators not supported for type 'system.string'" If I take out the distinct count part, it works. Is it not because I'm using the GROUP BY?
SELECT COUNT(EpaValue) AS [Leak Count], Location, EpaValue AS [Leak Desc.]
FROM ChartMes.dbo.RecourceActualEPA_Report
WHERE (EpaName = N'LEAK1') AND (Timestamp) > '20100429030000'
GROUP BY EpaValue, Location
ORDER BY Location, [Leak Count] DESC
Dim temp = (From p In db2.RecourceActualEPA_Reports _
Where (p.Timestamp >= str1stShiftStart) And (p.Timestamp < str2ndShiftCutoff) _
And (p.EpaName = "Leak1") _
Select p.EpaName.Distinct.Count(), p.Location, p.EpaValue)
p.EpaName seems to be a string, not a collection so you can't apply Count() there.
Here is the query you're trying to build (according to your SQL query) using LINQ (I'm not familiar with VB, so the query is written in C#):
var temp =
db2.RecourceActualEPA_Reports
.Where(p =>
p.Timestamp >= str1stShiftStart &&
p.Timestamp < str2ndShiftCutoff &&
p.EpaName == "Leak1"
).GroupBy(p => new { Key1 = p.EpaValue, Key2 = p.Location })
.Select(g => new
{
Count = g.Count(),
Value = g.Key.Key1,
Location = g.Key.Key2
}).OrderBy(i => new { i.Location, i.Count });
And please, in the future format and highlight your code using this, not (or not only) using VS/Management Studio.
Here is how it is formatted in SQL and in Visual Studio
SQL
SELECT COUNT(EpaValue) AS [Leak Count], Location, EpaValue AS [Leak Desc.]
FROM ChartMes.dbo.RecourceActualEPA_Report
WHERE (EpaName = N'LEAK1') AND (Timestamp) > '20100429030000'
GROUP BY EpaValue, Location
ORDER BY Location, [Leak Count] DESC
VB
Dim temp = (From p In db2.RecourceActualEPA_Reports _
Where (p.Timestamp >= str1stShiftStart) And (p.Timestamp < str2ndShiftCutoff) _
And (p.EpaName = "Leak1") _
Select p.EpaName.Distinct.Count(), p.Location, p.EpaValue)