Performing Subquery using Query Builder in Dataset C# - c#

I'm using this sql statement to produce the desired result. And would like to display those result query in my report in C# using rdlc via Dataset(.xsd).
SELECT pay.Cutoff,
emp.Id,
emp.LastName,
emp.FirstName,
emp.MiddleName,
emp.TinNumber,
job.Rate * 25 AS FixBIR,
(SELECT COUNT(*) AS MonthsWorked
FROM payroll AS pay3
WHERE YEAR(pay3.DateGenerated) = 2014
AND pay3.EmployeeId = 1
AND pay3.Cutoff = 1
ORDER BY MONTH(pay3.DateGenerated) ASC) * (job.Rate * 25)
AS MonthsWorked_FixBIR_TODATE,
pay.TaxWithheld,
(SELECT SUM(payroll2.TaxWithheld) AS TaxTotal
FROM employee AS employee2
INNER JOIN payroll AS payroll2
ON employee2.Id = payroll2.EmployeeId
WHERE (payroll2.Cutoff = 1)
AND (employee2.Id = emp.Id)
AND YEAR(payroll2.DateGenerated) = 2014)
AS Tax_TODATE,
YEAR(pay.DateGenerated) AS YEAR
FROM employee AS emp
INNER JOIN payroll AS pay
ON emp.Id = pay.EmployeeId
INNER JOIN job
ON emp.JobId = job.Id
WHERE pay.Cutoff = 1
AND pay.PayrollMonth = 'August'
AND Year(pay.DateGenerated) = 2014
This statement works fine (tested in navicat).
However, when I transferred this to Dataset using Query Builder it doesn't work. The error says:
The wizard detects the following problems when configuring the TableAdapter: "Fill" Details:
!Generated SELECT statement
Error in SELECT clause: expression near 'SELECT'
Error in SELECT clause: expression near 'FROM'
Missing FROM Clause
Error in SELECT clause: expression near ','.
Unable to parse query text
And if I try to use a simple subquery in the SELECT statement, an error says:
The query cannot be represented graphically in the Diagram and Criteria Pane.
What do I do for me to use the sql statement in rdlc? Are there other ways aside from query builder in dataset?

Related

C# "Conversion failed when converting date/time from character string" But query works well when run on server

I am incorporating a SQL Server query in C# and using a RDLC report to show query results. My query produces the correct result when run on SQL Server, but I get an error
Conversion failed when converting date/time from character string
when using it from C# code. I could not figure out why got this error. Please help me
C# code:
DateTime Date =DateTime.Parse(d2.Value.Date.ToString());
string format = "yyyy-MM-dd";
MessageBox.Show(Date.ToString(format));
this.soldItemsDetailsTableAdapter.Fill(this.Daily_Sales_Report.SoldItemsDetails, Date.ToString(format));
The error occurs on the last line of this code.
Date stored in database in format 'yyyy-MM-dd' and the above code produces date format as required as confirmed by the following code:
MessageBox.Show(Date.ToString(format));
SQL Server query:
SELECT
b.CompanyID, b.Category, a.ModelNo, a.ProductCode, a.Qty
FROM
(SELECT
s.DateSold, p.ProductID, p.ModelNo, p.ProductCode,
SUM(sipl.SubTotal) AS Qty
FROM
SalesInvoiceProductsList AS sipl
INNER JOIN
SalesInvoice AS s ON sipl.SalesInvoiceID = s.SalesInvoiceID
INNER JOIN
Product AS p ON sipl.ProductID = p.ProductID
GROUP BY
p.ModelNo, p.ProductCode, p.ProductID, s.DateSold) AS a
INNER JOIN
(SELECT DISTINCT
p.ProductID, p.CompanyID, cat.Category
FROM
Product AS p
INNER JOIN
Category AS cat ON p.CatID = cat.CatID
INNER JOIN
Company AS c ON p.CompanyID = c.CompanyID) AS b ON a.ProductID = b.ProductID
WHERE
(a.DateSold = #Date)
ORDER BY
b.CompanyID
If I use simple query which also takes date input instead of this complex query then got NO error. However his complex query works fine on SQL Server.
I resolved the issue by changing nothing except the query. Both queries executes well on server but the integration of first query issue the error under discussion but the following query does not issue any error, although the date format is same in both queries. I could not understand the reason. Can anybody explain why?
SELECT com.CompanyID AS company, c.Category, p.ModelNo AS Model, (sipl.SubTotal) AS Qty
FROM SalesInvoiceProductsList AS sipl
INNER JOIN SalesInvoice AS s ON sipl.SalesInvoiceID = s.SalesInvoiceID
INNER JOIN Product AS p ON sipl.ProductID = p.ProductID
INNER JOIN Company AS com ON p.CompanyID = com.CompanyID
INNER JOIN Category AS c ON p.CatID = c.CatID
WHERE (s.DateSold = #Date)
GROUP BY com.CompanyID, c.Category, p.ModelNo,sipl.SubTotal

Conversion of Sql query to linq

I am trying to convert sql query for select to linq query using EF in MVC but really got stuck with an error.
In SQL I'm able to get 6 records for my query,similarly when I try to convert this to linq it shows some error.
Following is my query in SQL:
SELECT
PurchaseOrderMaster.*, PurchaseOrderDetails.*, Vendor.*,
BusinessUnit.*, InvoiceMaster.*, TenantEmployee.*
FROM
PurchaseOrderMaster
INNER JOIN
PurchaseOrderDetails ON PurchaseOrderMaster.TenantID = PurchaseOrderDetails.TenantID
AND PurchaseOrderMaster.PurchaseOrderNumber = PurchaseOrderDetails.PurchaseOrderNumber
AND PurchaseOrderMaster.PurchaseOrderDate = PurchaseOrderDetails.PurchaseOrderDate
INNER JOIN
InvoiceMaster ON PurchaseOrderMaster.TenantID = InvoiceMaster.TenantID
AND PurchaseOrderMaster.PurchaseOrderNumber = InvoiceMaster.PurchaseOrderNumber
AND PurchaseOrderMaster.PurchaseOrderDate = InvoiceMaster.PurchaseOrderDate
INNER JOIN
BusinessUnit ON PurchaseOrderMaster.TenantID = BusinessUnit.TenantID
AND PurchaseOrderMaster.BusinessUnitID = BusinessUnit.BusinessUnitID
INNER JOIN
TenantEmployee ON PurchaseOrderMaster.TenantID = TenantEmployee.TenantID
INNER JOIN
Vendor ON PurchaseOrderMaster.TenantID = Vendor.TenantID
AND PurchaseOrderMaster.VendorID = Vendor.VendorID
For this query I am able to get 6 records .
And my linq query is:
return (from pom in db.PurchaseOrderMaster
join pod in db.PurchaseOrderDetails on pom.TenantID equals pod.TenantID
where pom.PurchaseOrderNumber == pod.PurchaseOrderNumber && pom.PurchaseOrderDate == pod.PurchaseOrderDate
join inv in db.InvoiceMaster on pom.TenantID equals inv.TenantID
where pom.PurchaseOrderNumber == inv.PurchaseOrderNumber && pom.PurchaseOrderDate == inv.PurchaseOrderDate
join bu in db.BusinessUnit on pom.BusinessUnitID equals bu.BusinessUnitID
join te in db.TenantEmployee on pom.TenantID equals te.TenantID
join v in db.Vendor on pom.TenantID equals v.TenantID
where pom.VendorID == v.VendorID
orderby pom.PurchaseOrderNumber ascending, pom.PurchaseOrderDate descending
select new { pom, pod, inv, bu, te, v }).ToList();
At the time of debugging,following is the error that I'm getting:
{"Invalid column name 'invoiceMasterModel_TenantID'.\r\nInvalid column name 'invoiceMasterModel_PurchaseOrderNumber'.\r\nInvalid column name 'invoiceMasterModel_PurchaseOrderDate'.\r\nInvalid column name 'invoiceMasterModel_InvoiceNumber'.\r\nInvalid column name 'invoiceMasterModel_InvoiceDate'.\r\nInvalid column name 'tenantEmployeeModel_TenantID'.\r\nInvalid column name 'tenantEmployeeModel_EmployeeID'."}
Inside Invoice Table it is not able to find some of the columns and hence throwing the error according to me..
I tried with many possible ways but was unable to solve this.
Any ideas..?
Problem was with my Entity.
What I did is,I added my entity again and according to that I recreated models for the associated tables removing the earlier ones.
It solved my problem finally .
I found this link Entity Framework 5 Invalid Column Name error related to somewhat similar problem.
Here also similar kind of error happened after the date time field. Check if your datetime field PurchaseOrderDate is nullable.
Many tools exist that can convert your sql queries to linq, in case you don't wanna write it urself. Try the following sites, works well in my case:
http://www.sqltolinq.com/
http://www.linqpad.net/

Using Subquery in System.Data.SqlCommand (C#) - Syntax Error, working in SQL Server Mgmt Studio

I got a query used by a Webservice which contains a subquery. When executing the query in SQL Server Management Studio, it works fine. However, using this in the webservice as a SqlCommand, I get:
System.Data.SqlClient.SqlException: Incorrect Syntax near the keyword 'JOIN'.
Incorrect Syntax near the keyword 'AS'.
Inserting extra characters let me figure out that the error refers to the position right after the subquery.
The query is as following:
SELECT H.H_ID AS ID, H.Name, TD.TDValue, A.A_ID, A_C.Value
FROM
H CROSS JOIN
A JOIN
(SELECT TD.A_ID, TD.H_ID, MAX(cast(TD.Version AS bigint)) AS Version FROM TD GROUP BY TD.A_ID, TD.H_ID) AS TData ON TData.H_ID = H.H_ID AND TData.A_ID = A.A_ID LEFT JOIN
TD2 ON TD2.H_ID = H.H_ID AND TD2.A_ID = A.A_ID AND TD2.Version = TData.Version LEFT JOIN
A_C ON A_C.A_ID = A.A_ID AND cast(A_C.R AS CHAR) = cast(TD.TDValue AS CHAR)
WHERE (H.Info = 1);
The Subquery is needed to get the last Version of an entry of the table TD.
If there are better ways to do that, feel free to let me know as well. :-)
Are there any limitations with the SqlCommand in C# that do not exist in MS SQL, or am I doing something wrong?
I would appreciate any help so much!
I would think that using a common table expression would be more efficient in this case. I'm not 100% that this is exactly what you need as I don't know your database structure and data needs, but this should help.
;with
cte_Tdata AS
(
SELECT
TD.A_ID
,TD.H_ID
,MAX(cast(TD.Version AS bigint)) AS Version
FROM
TD
GROUP BY
TD.A_ID
,TD.H_ID
),cte_TD AS
(
SELECT
TD.A_ID
,TD.H_ID
,TD.TDValue
FROM
TD
)
SELECT H.H_ID AS ID, H.Name, cte_TD.TDValue, A.A_ID, A_C.Value
FROM
H CROSS JOIN
A JOIN cte_Tdata ON cte_Tdata.H_ID = H.H_ID
AND cte_Tdata.A_ID = A.A_ID
INNER JOIN cte_TD ON cte_Tdata.H_ID = cte_TD.H_ID
AND cte_Tdata.A_ID = cte_TD.A_ID
LEFT JOIN A_C ON A_C.A_ID = A.A_ID
AND cast(A_C.R AS CHAR) = cast(cte_TD.TDValue AS CHAR)
LEFT JOIN TD2 ON TD2.H_ID = H.H_ID
AND TD2.A_ID = A.A_ID
AND TD2.Version = cte_Tdata.Version
WHERE
H.Info = 1;

LINQ Group by and having where clause

Below is the SQL Query I am trying to translate
SELECT dbo.Contracts.Supplier
FROM dbo.Contracts INNER JOIN dbo.Products ON dbo.Contracts.Product = dbo.Products.Product
where dbo.Products.ProductGroup='Crude'
GROUP BY dbo.Contracts.Supplier
Am I doing something wrong because I do not get same results with the following LINQ
var result = from c in context.Contracts
join p in context.Products on c.Product equals p.Product1
where p.Product1.Equals("Crude")
group c by c.Supplier into g
select new { supplier = g.Key };
It is generating a weird statement
SELECT
1 AS [C1],
[Distinct1].[Supplier] AS [Supplier]
FROM ( SELECT DISTINCT
[Extent1].[Supplier] AS [Supplier]
FROM [dbo].[Contracts] AS [Extent1]
WHERE N'Crude' = [Extent1].[Product]
) AS [Distinct1]
Using distinct would work but to get same results, LINQ should be generating a statement like so (it's like it is ignoring the join):
SELECT distinct dbo.Contracts.Supplier
FROM dbo.Contracts INNER JOIN dbo.Products ON dbo.Contracts.Product = dbo.Products.Product
where dbo.Products.ProductGroup='Crude'
I'm assuming that you are using 'EntityFramework' or 'Linq To SQL'. If so, you should be able to use navigation properties to navigate to product and filter invalit results out. This way your query might look something like this:
var result = (from c in context.Contracts
where c.Products.Any(p => p.ProductGroup == "Crude")
select c.Supplier).Distinct();
It will automatically convert into correct query (in this case possibly without join even, just using Exists sql keyword) and return distinct suppliers. This is if I understand your objective correctly - you want to obtain all suppliers assigned to contracts that contain product from 'Crude' product group.
Basically you should try to avoid using joins from linq to sql or linq to entities as much as possible when you can use navigation properties. System will probably be better at converting them into specific sql.

'Invalid column name [ColumnName]' on a nested linq query

Last update
After alot of testing, I realised that if i ran the same query over the same dataset (in this case a Northwind) table on SQL 2000 and SQL 2005, I get two different results.
On SQL 2000, i get the error that's in the question.
On SQL 2005, it succeeds.
So I've concluded that the query generated by linqpad doesn't work on sql 2000. To reproduce this, run:
OrderDetails
.GroupBy(x=>x.ProductID)
.Select(x=>new {product_id = x.Key, max_quantity = x.OrderByDescending(y=>y.UnitPrice).FirstOrDefault().Quantity}).Dump();
on a Northwind DB in sql 2000. The sql translation is:
SELECT [t1].[ProductID] AS [product_id], (
SELECT [t3].[Quantity]
FROM (
SELECT TOP 1 [t2].[Quantity]
FROM [OrderDetails] AS [t2]
WHERE [t1].[ProductID] = [t2].[ProductID]
ORDER BY [t2].[UnitPrice] DESC
) AS [t3]
) AS [max_quantity]
FROM (
SELECT [t0].[ProductID]
FROM [OrderDetails] AS [t0]
GROUP BY [t0].[ProductID]
) AS [t1]
Original Question
I've got the following query:
ATable
.GroupBy(x=> new {FieldA = x.FieldAID, FieldB = x.FieldBID, FieldC = x.FieldCID})
.Select(x=>new {FieldA = x.Key.FieldA, ..., last_seen = x.OrderByDescending(y=>y.Timestamp).FirstOrDefault().Timestamp})
results in:
SqlException: Invalid column name 'FieldAID' x 5
SqlException: Invalid column name 'FieldBID' x 5
SqlException: Invalid column name 'FieldCID' x 1
I've worked out it has to do with the last query to Timestamp because this works:
ATable
.GroupBy(x=> new {FieldA = x.FieldAID, FieldB = x.FieldBID, FieldC = x.FieldCID})
.Select(x=>new {FieldA = x.Key.FieldA, ..., last_seen = x.OrderByDescending(y=>y.Timestamp).FirstOrDefault()})
The query has been simplified. The purpose is to group by a set of variables and then show the last time this grouping occured in the db.
I'm using Linqpad 4 to generate these results so the Timestamp gives me a string whereas FirstOrDefault gives me the whole object which isn't ideal.
Update
On further testing I've noticed that the number and type of SQLException is related to the class created in the groupby clause.
So,
ATable
.GroupBy(x=> new {FieldA = x.FieldAID})
.Select(x=>new {FieldA = x.Key.FieldA, last_seen = x.OrderByDescending(y=>y.Timestamp).FirstOrDefault()})
results in
SqlException: Invalid column name 'FieldAID' x 5
You should use the SQL profiler to check if the SQL generated against the 2 databases is different.
We have only had two problems where something ran on SQL Server 2005 but not on SQL Server 2000. In both cases it was due to the lack of support for Multiple Active Result Sets (MARS) in SQL Server 2000. In one case it led to locking in the database, in the other case it led to a reduction of performance.

Categories