SqlCommand: Incorrect syntax near the keyword 'OVER' - sql

I'm trying to get data from database show it in a ASP.NET DataGrid.
It's showing the above mentioned error.
This is the select command:
public MasterJobList GetListForGrid(int RecCount, int PageNo, string OrderBy)
{
strSql = "WITH TempTable AS(Select JobDetails.JobCode,JobDetails.CurrentStatus,MasterModel.Name As ModelNumber,MasterModel.Code As ModelCode,MasterBrand.Code As BrandCode,MasterBrand.Name As BrandName,MasterDeviceType.Code As DeviceCode,MasterDeviceType.Name As DType,ROW_NUMBER() OVER (ORDER BY " + OrderBy + ") AS RowNumber From JobDetails JobDetails Inner Join MasterDeviceType ON JobDetails.DType = MasterDeviceType.Code Inner Join MasterBrand ON JobDetails.BCode = MasterBrand.Code Inner join MasterModel ON JobDetails.ModelNumber = MasterModel.Code WHERE 1 = 1) SELECT * FROM TempTable WHERE RowNumber BETWEEN {2} AND {3}";
MasterJobList objList = new MasterJobList();
DataTable dt = new DataTable();
dt = objDB.GetDataTableFromSQL(strSql);
if (dt != null)
{
foreach (DataRow Dr in dt.Rows)
{
jobs obj = new jobs();
obj.JobCode =Convert.ToInt32(Dr["JobCode"].ToString());
if (Dr["DType"] != DBNull.Value)
obj.DType = Dr["DType"].ToString();
else
obj.DType = "";
if (Dr["BrandName"] != DBNull.Value)
obj.BrandName = Dr["BrandName"].ToString();
else
obj.BrandName = "";
if (Dr["ModelNumber"] != DBNull.Value)
obj.ModelNumber = Dr["ModelNumber"].ToString();
else
obj.ModelNumber = "";
if (Dr["CurrentStatus"] != DBNull.Value)
obj.CurrentStatus = Dr["CurrentStatus"].ToString();
else
obj.CurrentStatus = "";
objList.Add(obj);
}
}
return objList;
}
The exact error is:
Exception Details: System.Data.SqlClient.SqlException: Incorrect
syntax near the keyword 'OVER'.
Please look my full code...

Your ROW_NUMBER-"column" comes after the JOINs.
Change it to:
string sql = #"
WITH TempTable AS
(
Select
JobDetails.JobCode,
JobDetails.CurrentStatus,
MasterModel.Name As ModelNumber,
MasterModel.Code As ModelCode,
MasterBrand.Code As BrandCode,
MasterBrand.Name As BrandName,
MasterDeviceType.Code As DeviceCode,
MasterDeviceType.Name As DType,
ROW_NUMBER() OVER (ORDER BY {0}) AS RowNumber
From JobDetails JobDetails
Inner Join MasterDeviceType
ON JobDetails.DType = MasterDeviceType.Code
Inner Join MasterBrand
ON JobDetails.BCode = MasterBrand.Code
Inner join MasterModel
ON JobDetails.ModelNumber = MasterModel.Code,
WHERE {1}
)
SELECT * FROM TempTable WHERE RowNumber BETWEEN {2} AND {3}";
Now use sql = String.Format(sql, orderBy, filter, rnStart, rnEnd) to assign the values.
The variables could be:
string orderBy = "ModelNumber ASC";
string filter = "BrandName = 'Sony'";
int rnStart = PageNo == 1 ? 1 : ((PageNo - 1) * RecCount) + 1;
int rnEnd = PageNo == 1 ? RecCount : PageNo * RecCount;
Update: to show the complete method (at least the relevant code) according to your edit.
public MasterJobList GetListForGrid(int RecCount, int PageNo, string OrderBy)
{
string strSql = #"
WITH TempTable AS
(
Select
JobDetails.JobCode,
JobDetails.CurrentStatus,
MasterModel.Name As ModelNumber,
MasterModel.Code As ModelCode,
MasterBrand.Code As BrandCode,
MasterBrand.Name As BrandName,
MasterDeviceType.Code As DeviceCode,
MasterDeviceType.Name As DType,
ROW_NUMBER() OVER (ORDER BY {0}) AS RowNumber
From JobDetails JobDetails
Inner Join MasterDeviceType
ON JobDetails.DType = MasterDeviceType.Code
Inner Join MasterBrand
ON JobDetails.BCode = MasterBrand.Code
Inner join MasterModel
ON JobDetails.ModelNumber = MasterModel.Code,
WHERE {1}
)
SELECT * FROM TempTable WHERE RowNumber BETWEEN {2} AND {3}";
int rnStart = PageNo == 1 ? 1 : ((PageNo - 1) * RecCount) + 1;
int rnEnd = PageNo == 1 ? RecCount : PageNo * RecCount;
strSql = String.Format(strSql, OrderBy, "1=1", rnStart, rnEnd);
DataTable dt = objDB.GetDataTableFromSQL(strSql);
// ...
return objList;
}

please check this example in ssms and change the accordingly.
declare #t table(name varchar(50))
insert into #t values ('a'),('b'),('c'),('d'),('e')
select ROW_NUMBER() over ( order by name)
, name
from #t
Check the comment, you just apply the "orderby" by value
WITH temptable
AS (SELECT jobdetails.jobcode,
jobdetails.currentstatus,
mastermodel.NAME AS ModelNumber,
mastermodel.code AS ModelCode,
masterbrand.code AS BrandCode,
masterbrand.NAME AS BrandName,
masterdevicetype.code AS DeviceCode,
masterdevicetype.NAME AS DType,
Row_number()
OVER (
ORDER BY " + orderby + ") AS RowNumber --here you have to assign the order by value
FROM jobdetails JobDetails
INNER JOIN masterdevicetype
ON jobdetails.dtype = masterdevicetype.code
INNER JOIN masterbrand
ON jobdetails.bcode = masterbrand.code
INNER JOIN mastermodel
ON jobdetails.modelnumber = mastermodel.code
WHERE 1 = 1)
SELECT *
FROM temptable
WHERE rownumber BETWEEN {2} AND {3}

Related

I use this and get the message like [305]: single-row query returns more than one row:

I use this and get the message like [305]: single-row query returns more than one row:
with catregion as(
select ll.ID, crm.catid, crm.catname,
SUBSTR_REGEXPR('[^_]+' IN "REGIONNAME" OCCURRENCE 3) AS "attr_id", crm.attrname, ll.valint, ll.valreal, ll.valdate, valstr, vallong, VerNum
from CATREGIONMAP crm
join LLAttrData ll on ll.defid = crm.catid and ll.attrid = SUBSTR_REGEXPR('[^_]+' IN "REGIONNAME" OCCURRENCE 3)
WHERE attrname in ('Номер документа SAP','Статус OpenText','Статус документа (SAP)')
),
myselect as(
select DT.DATAID AS cardId,
(select VALSTR from catregion a where a.catname = 'Атрибуты SAP' and a.attrname = 'Номер документа SAP' AND a.id = DT.DATAID) AS SAP_number,
(select VALSTR from catregion a where a.catname = 'Договор_основные' and a.attrname = 'Статус OpenText' AND a.id = DT.DATAID) as OpenText_status,
(select VALSTR from catregion a where a.catname = 'Договор_основные' and a.attrname = 'Статус документа (SAP)' AND a.id = DT.DATAID) as SAP_status
FROM DTREE DT)
SELECT * FROM myselect WHERE SAP_number IN ('SHP000000000000001110002850800000','SHD000000000000001120000682900000','SHP000000000000001110002738900000')
You need to make your select VALSTR from catregion a ... subqueries to return only one value by adding additional conditions to exclude the extra lines or by sorting and taking TOP 1.
To see what exactly is causing the issue run the subqueries and see which one returns more than one row:
select id, count(*) from catregion
where catname = 'Атрибуты SAP' and attrname = 'Номер документа SAP'
group by id having count(*) > 1;
select id, count(*) from catregion
where catname = 'Договор_основные' and attrname = 'Статус OpenText'
group by id having count(*) > 1;
select id, count(*) from catregion
where catname = 'Договор_основные' and attrname = 'Статус документа (SAP)'
group by id having count(*) > 1;

incorrect syntax in over and partition by with temporary tables

I have a partition-by function in my stored procedure which calls for a temporary table from a previous partition-by function. The table that I created with the previous partition by function is #tempVehicleManifestRow which in turn is what I call for the next partition by function. What happens is that it shoes the error
"incorrect syntax near ' #tempVehicleManifestRow'"
Why is this happening? Isn't it that I have already generated a temporary table with the data needed even before I actually selected it?
I have attached below the partition by functions I used.
This is my first partition by function:
;WITH A AS
(
SELECT ROW_NUMBER() OVER(ORDER BY
CASE
when #pOrderby = 'SortByGender' then T.Gender
when #pOrderby = 'SortByCost' then T.colCostCenterCodeVarchar
when #pOrderby = 'SortByPickupDate' then cast(T.colPickUpDate as varchar(20))
when #pOrderby = 'SortByLastName' then T.LastName
when #pOrderby = 'SortByFirstName' then T.FirstName
when #pOrderby = 'SortByEmployeeID' then cast(T.colSeafarerIdInt as varchar(20))
when #pOrderby = 'SortByShip' then T.VesselName
when #pOrderby = 'SortByTitle' then T.RankName
when #pOrderby = 'SortByRouteFrom' then T.RouteFrom
when #pOrderby = 'SortByRouteTo' then T.RouteTo
when #pOrderby = 'SortByFromCity' then T.colFromVarchar
when #pOrderby = 'SortByToCity' then T.colToVarchar
when #pOrderby = 'SortByVehicleTypeName' then T.VehicleTypeName
when #pOrderby = 'SortByStatus' then T.VehicleTypeName
when #pOrderby = 'SortByCostCenter' then T.colCostCenterCodeVarchar
when #pOrderby = 'SortByNationality' then T.Nationality
when #pOrderby = 'SortByVehicleVendor' then T.VehicleVendorname
when #pOrderby = 'SortByRecordLocator' then T.colRecordLocatorVarchar
when #pOrderby = 'SortByOnOffdate' then cast(T.colOnOffDate as varchar(20))
when #pOrderby = 'SortByPickupTime' then cast(T.colPickUpTime as varchar(20))
when #pOrderby = 'SortByOnOff' then T.colSFStatus
when #pOrderby = 'SortByHotel' then T.HotelVendorName
ELSE
T. VehicleVendorname
END ,
CASE WHEN #pOrderby = 'SortByPickupDate' then cast(T.colPickUpTime as varchar(20))
ELSE T.FirstName
END
) AS xRow,
* FROM #tempVehicleManifest T
) SELECT * INTO #tempVehicleManifestRow FROM A ORDER BY A.xRow
This is the partition-by that is are having problems:
;WITH CC AS
(
SELECT ROW_NUMBER() OVER(PARTITION BY CC.colRecordLocatorVarchar, CC.colSeafarerIdInt,
CC.colOnOffVarchar , CC.colVehicleVendorIDInt
ORDER BY CC.colTagIDInt DESC) xRow, CC.*
FROM (
SELECT distinct
A.xRow,
A.colTransVehicleIDBigint,
A.colSeafarerIdInt, A.LastName, A.FirstName,
A.colIdBigint, A.colTravelReqIDInt,
A.colRecordLocatorVarchar, A.colOnOffDate,
A.colRequestIDInt, A.colVehicleVendorIDInt,
A.VehicleVendorname, A.colVehiclePlateNoVarchar,
A.colPickUpDate, A.colPickUpTime,
A.colDropOffDate, A.colDropOffTime,
A.colConfirmationNoVarchar, A.colVehicleStatusVarchar,
A.colVehicleTypeIdInt, A.VehicleTypeName, A.colSFStatus,
A.colRouteIDFromInt, A.RouteFrom, A.colRouteIDToInt, A.RouteTo,
A.colFromVarchar, A.colToVarchar, A.colRemarksForAuditVarchar,
A.colHotelIDInt, A.HotelVendorName, A.colRankIDInt, A.RankName,
A.colCostCenterIDInt, A.colCostCenterCodeVarchar,
Nationality = RTRIM(LTRIM(N.colNationalityCodeVarchar)) + '-' + RTRIM(LTRIM(N.colNationalityDescriptionVarchar)),
A.colIsVisibleBit,
A.colContractIdInt, A.Gender, A.colVesselIdInt,
A.VesselName, UserID = #pUserID, A.colSeqNoInt
, A.colDriverIDInt
--, A.colIsNoVehicleNeeded
, A.colVehicleDispatchTime
, FlightNo =A.colFlightNoVarchar
, Carrier = A.colMarketingAirlineCodeVarchar
, Departure = A.colDepartureAirportLocationCodeVarchar
, Arrival = A.colArrivalAirportLocationCodeVarchar
, DeptDate = A.colDepartureDateTime
, ArrDate = A.colArrivalDateTime
, PA.PassportNo
, PA.PassportExp
, PA.PassportIssued
, BR.Birthday
, ISNULL(CC.colIsActiveBit,0) as colIsActiveBitTagged
, CC.colCreatedByVarchar as createdUserTag
, CC.colModifiedByVarchar as modifiedUserTag
, CC.colVehicleVendorIDInt as taggedVehicleVendorId
#tempVehicleManifestRow A
LEFT JOIN TblVehicleManifestConfirmed B ON
A.colSeafarerIdInt = B.colSeafarerIdInt AND
A.colVehicleVendorIDInt = B.colVehicleVendorIDInt AND
A.colPickUpDate = B.colPickUpDate AND
ISNULL(A.colRecordLocatorVarchar,'') = ISNULL(B.colRecordLocatorVarchar,'')
AND A.colRouteIDFromInt = B.colRouteIDFromInt
AND A.colRouteIDToInt = B.colRouteIDToInt
--not visible to vendor but not realy cancelled
LEFT JOIN TblVehicleManifestConfirmed Hide ON
A.colSeafarerIdInt = Hide.colSeafarerIdInt AND
A.colVehicleVendorIDInt = Hide.colVehicleVendorIDInt AND
A.colPickUpDate = Hide.colPickUpDate AND
ISNULL(A.colRecordLocatorVarchar,'') = ISNULL(Hide.colRecordLocatorVarchar,'') AND
ISNULL(Hide.colIsVisibleBit,1) = 0
AND A.colRouteIDFromInt = B.colRouteIDFromInt
AND A.colRouteIDToInt = B.colRouteIDToInt
--added new table
LEFT JOIN TblTag_Vehicle CC ON B.colIdBigint = CC.colIdBigint AND
B.colTravelReqIDInt = CC.colTravelReqIDInt AND B.colSeafarerIdInt = CC.colSeafarerIdInt
--end new added table
LEFT JOIN dbo.TblVehiclePlates VP ON VP.colPlateID = B.colVehiclePlateNoVarchar
LEFT JOIN dbo.TblSeafarer S ON S.colSeafarerIdInt = A.colSeafarerIdInt
LEFT JOIN TblNationality N ON N.colNatioalityIdInt = S.colNationalityIDInt
LEFT JOIN #TempPassport PA ON A.colSeafarerIdInt = PA.SeafarerId
LEFT JOIN tmRemarks_Birthday BR ON BR.FK_ItineraryRefID = A.colRecordLocatorVarchar
JOIN #tempVehicleVendor VE ON VE.colVehicleVendorIDInt = A.colVehicleVendorIDInt
WHERE
( B.colConfirmedManifestIDBigint IS NULL
OR
Hide.colTransVehicleIDBigint IS NOT NULL
)
ORDER BY A.xRow
)
) SELECT * INTO #tempManifestNew
You have missed the FROM CLAUSE in this query near #tempVehicleManifestRow A. Here is the correct query.
;WITH CC
AS (
SELECT ROW_NUMBER() OVER (
PARTITION BY CC.colRecordLocatorVarchar
,CC.colSeafarerIdInt
,CC.colOnOffVarchar
,CC.colVehicleVendorIDInt ORDER BY CC.colTagIDInt DESC
) xRow
,CC.*
FROM (
SELECT DISTINCT A.xRow
,A.colTransVehicleIDBigint
,A.colSeafarerIdInt
,A.LastName
,A.FirstName
,A.colIdBigint
,A.colTravelReqIDInt
,A.colRecordLocatorVarchar
,A.colOnOffDate
,A.colRequestIDInt
,A.colVehicleVendorIDInt
,A.VehicleVendorname
,A.colVehiclePlateNoVarchar
,A.colPickUpDate
,A.colPickUpTime
,A.colDropOffDate
,A.colDropOffTime
,A.colConfirmationNoVarchar
,A.colVehicleStatusVarchar
,A.colVehicleTypeIdInt
,A.VehicleTypeName
,A.colSFStatus
,A.colRouteIDFromInt
,A.RouteFrom
,A.colRouteIDToInt
,A.RouteTo
,A.colFromVarchar
,A.colToVarchar
,A.colRemarksForAuditVarchar
,A.colHotelIDInt
,A.HotelVendorName
,A.colRankIDInt
,A.RankName
,A.colCostCenterIDInt
,A.colCostCenterCodeVarchar
,Nationality = RTRIM(LTRIM(N.colNationalityCodeVarchar)) + '-' + RTRIM(LTRIM(N.colNationalityDescriptionVarchar))
,A.colIsVisibleBit
,A.colContractIdInt
,A.Gender
,A.colVesselIdInt
,A.VesselName
,UserID = #pUserID
,A.colSeqNoInt
,A.colDriverIDInt
--, A.colIsNoVehicleNeeded
,A.colVehicleDispatchTime
,FlightNo = A.colFlightNoVarchar
,Carrier = A.colMarketingAirlineCodeVarchar
,Departure = A.colDepartureAirportLocationCodeVarchar
,Arrival = A.colArrivalAirportLocationCodeVarchar
,DeptDate = A.colDepartureDateTime
,ArrDate = A.colArrivalDateTime
,PA.PassportNo
,PA.PassportExp
,PA.PassportIssued
,BR.Birthday
,ISNULL(CC.colIsActiveBit, 0) AS colIsActiveBitTagged
,CC.colCreatedByVarchar AS createdUserTag
,CC.colModifiedByVarchar AS modifiedUserTag
,CC.colVehicleVendorIDInt AS taggedVehicleVendorId
-- HERE YOU HAVE MISSED FROM CLAUSE
FROM #tempVehicleManifestRow A
LEFT JOIN TblVehicleManifestConfirmed B ON A.colSeafarerIdInt = B.colSeafarerIdInt
AND A.colVehicleVendorIDInt = B.colVehicleVendorIDInt
AND A.colPickUpDate = B.colPickUpDate
AND ISNULL(A.colRecordLocatorVarchar, '') = ISNULL(B.colRecordLocatorVarchar, '')
AND A.colRouteIDFromInt = B.colRouteIDFromInt
AND A.colRouteIDToInt = B.colRouteIDToInt
--not visible to vendor but not realy cancelled
LEFT JOIN TblVehicleManifestConfirmed Hide ON A.colSeafarerIdInt = Hide.colSeafarerIdInt
AND A.colVehicleVendorIDInt = Hide.colVehicleVendorIDInt
AND A.colPickUpDate = Hide.colPickUpDate
AND ISNULL(A.colRecordLocatorVarchar, '') = ISNULL(Hide.colRecordLocatorVarchar, '')
AND ISNULL(Hide.colIsVisibleBit, 1) = 0
AND A.colRouteIDFromInt = B.colRouteIDFromInt
AND A.colRouteIDToInt = B.colRouteIDToInt
--added new table
LEFT JOIN TblTag_Vehicle CC ON B.colIdBigint = CC.colIdBigint
AND B.colTravelReqIDInt = CC.colTravelReqIDInt
AND B.colSeafarerIdInt = CC.colSeafarerIdInt
--end new added table
LEFT JOIN dbo.TblVehiclePlates VP ON VP.colPlateID = B.colVehiclePlateNoVarchar
LEFT JOIN dbo.TblSeafarer S ON S.colSeafarerIdInt = A.colSeafarerIdInt
LEFT JOIN TblNationality N ON N.colNatioalityIdInt = S.colNationalityIDInt
LEFT JOIN #TempPassport PA ON A.colSeafarerIdInt = PA.SeafarerId
LEFT JOIN tmRemarks_Birthday BR ON BR.FK_ItineraryRefID = A.colRecordLocatorVarchar
JOIN #tempVehicleVendor VE ON VE.colVehicleVendorIDInt = A.colVehicleVendorIDInt
WHERE (
B.colConfirmedManifestIDBigint IS NULL
OR Hide.colTransVehicleIDBigint IS NOT NULL
)
) AS x -- missing alias declaration, required in TSQL
)
SELECT *
INTO #tempManifestNew

Error in JPQL Query: "unexpected token: ( near line 1"

i have this working sql query:
select temp.pratica_regola_id FROM ( SELECT TABLE1.pratica_regola_id, TABLE1.CON FROM ( SELECT pratica_regola_id, COUNT(*) AS CON FROM (SELECT DISTINCT PRATICA_REGOLA_ID, ENTITA_LEGAME_ID FROM legame_regola_pratica L1 LEFT JOIN (select LRP.entita_legame_id AS EL1 from legame_regola_pratica LRP JOIN entita_legame EL ON LRP.entita_legame_id = EL.entita_legame_id where LRP.pratica_regola_id = 418 AND LRP.REGOLA_ID = 1426 AND el.tp_entita_legame_id =1 ) TAB_ENT_LEG ON TAB_ENT_LEG.EL1 = L1.entita_legame_id WHERE TAB_ENT_LEG.EL1 IS NOT NULL AND l1.tp_livello_legame_id = 2 and l1.pratica_regola_id in (select pratica_regola_id from pratica_regola where tp_stato_pratica_id = 2)) GROUP BY PRATICA_REGOLA_ID ) TABLE1 INNER JOIN ( SELECT pratica_regola_id, COUNT(*) AS TOT FROM (SELECT DISTINCT PRATICA_REGOLA_ID, ENTITA_LEGAME_ID FROM legame_regola_pratica L1) group by pratica_regola_id) TABLE2 on TABLE1.pratica_regola_id = TABLE2.pratica_regola_id where TABLE1.CON = TABLE2.TOT) temp WHERE CON = (SELECT COUNT(*) FROM legame_regola_pratica where pratica_regola_id = 418 AND REGOLA_ID = 1426 and dat_ora_can is null) and pratica_regola_id <> 418;
I tried to tranlsate it in JPQL in this kind:
#Query("SELECT TABLE_TEMP_1.praticaRegolaId FROM ("
+ "SELECT TABLE_TEMP_2.praticaRegolaId, TABLE_TEMP_2.numero_entita FROM ("
+ "SELECT praticaRegolaId, COUNT(*) AS numero_entita FROM (SELECT DISTINCT PraticaRegola.praticaRegolaId, EntitaLegame.entitaLegameId FROM LegameRegolaPratica LRP_1 LEFT JOIN ("
+ "SELECT LRP.entitaLegame.entitaLegameId AS EL_1 FROM LegameRegolaPratica LRP JOIN EntitaLegame EL ON LRP.entitaLegame.entitaLegameId = EL.entitaLegameId"
+ "WHERE LRP.praticaRegola = :praticaRegola AND LRP.regola = :praticaRegola.regola AND EL.tpEntitaLegame = :tipoEntitaLegame)"
+ "TAB_ENT_LEG ON TAB_ENT_LEG.EL_1 = LRP_1.entitaLegame.entitaLegameId WHERE TAB_ENT_LEG.EL_1 IS NOT NULL AND LRP_1.tpLivelloLegame = :tipoLivelloLegame AND LRP_1.praticaRegola.praticaRegolaId IN (SELECT praticaRegolaId FROM"
+ " praticaRegola WHERE tpStatoPratica = :tipoStatoPratica))"
+ "GROUP BY praticaRegolaId) AS TABLE_TEMP_2"
+ "INNER JOIN ("
+ "SELECT praticaRegolaId, COUNT(*) AS TOT FROM (SELECT DISTINCT LRP_1.praticaRegola.praticaRegolaId, LRP_1.entitaLegame.entitaLegameId FROM LegameRegolaPratica LRP_1) GROUP BY praticaRegolaId"
+ ") TABLE_TEMP_3" + "ON TABLE_TEMP_2.praticaRegolaId = TABLE_TEMP_3.praticaRegolaId" + "WHERE TABLE_TEMP_2.NUMERO_ENTITA = TABLE_TEMP_3.TOT )"
+ "AS TABLE_TEMP_1 WHERE NUMERO_ENTITA = (SELECT COUNT(*) FROM LegameRegolaPratica WHERE praticaRegola = :praticaRegola"
+ "AND regola = :praticaRegola.regola AND dataOraCancellazione IS NULL) ")
but i get this error message:
Caused by: org.hibernate.hql.internal.ast.QuerySyntaxException: unexpected token: ( near line 1, column 42 [SELECT TABLE_TEMP_1.praticaRegolaId FROM (SELECT TABLE_TEMP_2.praticaRegolaId, TABLE_TEMP_2.numero_entita FROM (SELECT praticaRegolaId, COUNT(*) AS numero_entita FROM (SELECT DISTINCT PraticaRegola.praticaRegolaId, EntitaLegame.entitaLegameId FROM it.aivebst.adaprice.rules.entities.LegameRegolaPratica LRP_1 LEFT JOIN (SELECT LRP.entitaLegame.entitaLegameId AS EL_1 FROM it.aivebst.adaprice.rules.entities.LegameRegolaPratica LRP JOIN EntitaLegame EL ON LRP.entitaLegame.entitaLegameId = EL.entitaLegameIdWHERE LRP.praticaRegola = :praticaRegola AND LRP.regola = :praticaRegola.regola AND EL.tpEntitaLegame = :tipoEntitaLegame)TAB_ENT_LEG ON TAB_ENT_LEG.EL_1 = LRP_1.entitaLegame.entitaLegameId WHERE TAB_ENT_LEG.EL_1 IS NOT NULL AND LRP_1.tpLivelloLegame = :tipoLivelloLegame AND LRP_1.praticaRegola.praticaRegolaId IN (SELECT praticaRegolaId FROM praticaRegola WHERE tpStatoPratica = :tipoStatoPratica))GROUP BY praticaRegolaId) AS TABLE_TEMP_2INNER JOIN (SELECT praticaRegolaId, COUNT(*) AS TOT FROM (SELECT DISTINCT LRP_1.praticaRegola.praticaRegolaId, LRP_1.entitaLegame.entitaLegameId FROM it.aivebst.adaprice.rules.entities.LegameRegolaPratica LRP_1) GROUP BY praticaRegolaId) TABLE_TEMP_3ON TABLE_TEMP_2.praticaRegolaId = TABLE_TEMP_3.praticaRegolaIdWHERE TABLE_TEMP_2.NUMERO_ENTITA = TABLE_TEMP_3.TOT )AS TABLE_TEMP_1 WHERE NUMERO_ENTITA = (SELECT COUNT(*) FROM it.aivebst.adaprice.rules.entities.LegameRegolaPratica WHERE praticaRegola = :praticaRegolaAND regola = :praticaRegola.regola AND dataOraCancellazione IS NULL) ]
at org.hibernate.hql.internal.ast.QuerySyntaxException.convert(QuerySyntaxException.java:54)
at org.hibernate.hql.internal.ast.QuerySyntaxException.convert(QuerySyntaxException.java:47)
Thank you
You may not have subqueries in the from clause of a HQL query. Use a native SQL query.
Quote from the documentation:
Note that HQL subqueries can occur only in the select or where clauses.

SQL into LINQ... need a nudge in the right direction

I want to use LINQ as a DataGrivdView Datasource... I have the correct SQL query, but I'm having a heck of a time re-writing it in LINQ...
SQL:
SELECT ICITEM.ITEMNO, ICITEM.[DESC], MAX(PORCPL.DTARRIVAL) AS Expr1
FROM ICITEM INNER JOIN
PORCPL ON PORCPL.ITEMNO = ICITEM.ITEMNO
WHERE (ICITEM.ITEMNO LIKE '%R001%')
GROUP BY ICITEM.ITEMNO, ICITEM.[DESC]
My feeble attempt(s) at LINQ:
Dim s = From items In db.ICITEMs
Where items.ITEMNO.Contains(Me.txtQuery.Text) Or items.DESC.Contains(Me.txtQuery.Text)
Join recDates In db.PORCPLs On items.ITEMNO Equals recDates.ITEMNO
Select [Item_ID] = items.ITEMNO, [Description] = items.DESC, [rd] = recDates.DTARRIVAL
My LINQ Log...
SELECT [t0].[ITEMNO] AS [Item_ID], [t0].[DESC] AS [Description], [t1].[DTARRIVAL] AS [rd]
FROM [dbo].[ICITEM] AS [t0]
INNER JOIN [dbo].[PORCPL] AS [t1] ON [t0].[ITEMNO] = [t1].[ITEMNO]
WHERE ([t0].[ITEMNO] LIKE #p0) OR ([t0].[DESC] LIKE #p1)
-- #p0: Input VarChar (Size = 8000; Prec = 0; Scale = 0) [%r001%]
-- #p1: Input VarChar (Size = 8000; Prec = 0; Scale = 0) [%r001%]
-- Context: SqlProvider(Sql2008) Model: AttributedMetaModel Build: 4.0.30319.1
I can't figure out how to get a Max function on the [rd] field... ANY insight would be most appreciated.
You need to add a Group By.
Here is an example which should help:
Dim s = From items In db.ICITEMs
Where items.ITEMNO.Contains(Me.txtQuery.Text) Or items.DESC.Contains(Me.txtQuery.Text)
Join recDates In db.PORCPLs On items.ITEMNO Equals recDates.ITEMNO
Group By items.ITEMNO, items.DESC Into MaxArrivalDate = Max(recDates.DTARRIVAL)
Select [Item_ID] = items.ITEMNO, [Description] = items.DESC, [rd] = MaxArrivalDate
You have an additional Contains in your linq query. If this is correct, here is the full linq query with group by and max:
Dim s = From items In db.ICITEMs
Where items.ITEMNO.Contains(Me.txtQuery.Text) Or items.DESC.Contains(Me.txtQuery.Text)
Join recDates In db.PORCPLs On items.ITEMNO Equals recDates.ITEMNO
Group By items.ITEMNO, items.DESC Into Group
Let MaxArrival = Group.Max(Function(p) p.recDates.DTARRIVAL)
Select [Item_ID] = ITEMNO, [Description] = DESC, [rd] = MaxArrival

SQL Server - Multiple Select with Duplicate Names

I'm trying to grab some data from my SQL database as below;
USE exampleDatabase
SELECT TOP(1) [Name] FROM [Peeps] ORDER BY [Weight] DESC
SELECT TOP(1) [Name] FROM [Peeps] ORDER BY [Age] DESC
The problem is when I read the data I get an error 'Name'.
Dim byWeight As String = sqlReader.GetValue(sqlReader.GetOrdinal("Name"))
Dim byAge As String = sqlReader.GetValue(sqlReader.GetOrdinal("Name"))
How would I read this data as above considering I can't use name twice?
I think you are missing a semi-colon after the first SELECT statement. Here's a sample app I put together (note the semicolon in my sql statement):
var sql = "Select TOP 1 name from sys.columns;"
+ "Select TOP 1 name from sys.objects";
var firstname = string.Empty;
var secondname = string.Empty;
var connString = ConfigurationManager.ConnectionStrings["Test"].ConnectionString;
using ( var conn = new SqlConnection( connString ) )
{
conn.Open();
using ( var cmd = new SqlCommand( sql, conn ) )
{
var reader = cmd.ExecuteReader();
if ( reader == null )
return;
if ( reader.Read() )
firstname = reader.GetString( reader.GetOrdinal( "Name" ) );
reader.NextResult();
if ( reader.Read() )
secondname = reader.GetString( reader.GetOrdinal( "Name" ) );
}
}
Response.Write( firstname + "<br />" );
Response.Write( secondname + "<br />" );
You can achieve the same goal as the semi-colon by using the "GO keyword like so:
var sql = "Select TOP (1) name from sys.columns GO "
+ "Select TOP (1) name from sys.objects";
You can use the 'as' keyword to rename columns in your results, like so:
SELECT TOP(1) [Name] AS ByWeight FROM [Peeps] ORDER BY [Weight] DESC
hmmm... well you could make it one select statement....
USE exampleDatabase
SELECT W.[Name] AS W_Name, A.[Name] AS A_Name FROM
(SELECT TOP(1) [Name] FROM [Peeps] ORDER BY [Weight] DESC) W
JOIN (SELECT TOP(1) [Name] FROM [Peeps] ORDER BY [Age] DESC) A
What if you UNION your SQL together into one result set?
USE exampleDatabase
SELECT TOP(1) [Name] FROM [Peeps] ORDER BY [Weight] DESC
UNION ALL
SELECT TOP(1) [Name] FROM [Peeps] ORDER BY [Age] DESC