SQL not ran by JDBC but perfectly functional in Database Clients - sql

I have a query to select tree structure data from SQL Server 2012 to fetch tree structured resultset from one table.
This is the SQL I used:
with cte_child (id, parentId, contractId, contractName, jfCompany, jfDepartment, yfDepartment, totalAmount, signDate, lvl)
as
(
select
id, parentId, contractId, contractName,
jfCompany, jfDepartment, yfDepartment, totalAmount, signDate, 0
from
Contract_info_main
where
contractId = 'c2012-0412'
union all
select
c.id, c.parentId, c.contractId, c.contractName,
c.jfCompany, c.jfDepartment, c.yfDepartment, c.totalAmount,
c.signDate, s.lvl+1
from
Contract_info_main c
inner join
cte_child s on s.parentId = c.id
)
select * from cte_child
This SQL statement does run with correct result on local SQL Server 2012 database, as well as my local machine with DBeaver client. The driver used by DBeaver is "mssql-jdbc:7.4.1.jre8".
The weird thing is when I use pure Java code to send identical SQL string to send exactly same query, it fails with an error
object name 'Contract_inf_main' is invalid
Since I am using Ubuntu 18, I guess DLL along with Driver should not be a problem? but what could be possible cause of this problem? thanks
This is my JDBC code:
public static void main(String[] args) throws ClassNotFoundException, SQLException {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
final Connection connection = DriverManager.getConnection("jdbc:sqlserver://192.168.5.158:1433", "general_reader", "sqlserver2017#reader");
final String sql = "with cte_child(id, parentId, contractId, contractName, jfCompany, jfDepartment, yfDepartment, totalAmount, signDate, lvl) " +
"as (select id, parentId, contractId, contractName, jfCompany, jfDepartment, yfDepartment, totalAmount, signDate, 0 " +
"from Contract_info_main where contractId = 'jy2012-041' " +
"union all select c.id, c.parentId, c.contractId, c.contractName, c.jfCompany, c.jfDepartment, c.yfDepartment, c.totalAmount, c.signDate, s.lvl+1 " +
"from Contract_info_main c inner join cte_child s on s.parentId = c.id) select * from cte_child";
final PreparedStatement statement = connection.prepareStatement(sql);
System.out.println(sql);
final ResultSet resultSet = statement.executeQuery();
while(resultSet.next()) {
System.out.println("id = " + resultSet.getString(1) + " and parentId = " + resultSet.getString(2));
}
resultSet.close();
statement.close();
connection.close();
}

Related

SQL query grammatical exception on converting recursive query to JPQL

This is a JPQl query created from the below mentioned SQL query:
SELECT * FROM NursingSectionHead head where head.secCode IN (" +
"WITH NUR_SECTIONS_SEC_CODE (secCode) " +
"AS (SELECT secCode " +
"FROM NursingSection " +
"WHERE secCode = (SELECT loc.nursingSecCode FROM LocationMast loc WHERE loc.id.locCode = :locCode) " +
"UNION ALL " +
"SELECT C1.secCode " +
"FROM NursingSection C1 " +
"INNER JOIN NUR_SECTIONS_SEC_CODE C2 ON C1.prevSec = C2.secCode)" +
"SELECT * FROM NUR_SECTIONS_SEC_CODE)
This is the SQL query:
select * from IR_TB_NUR_SEC_HEAD head where HEAD.SEC_CODE IN (
WITH NUR_SECTIONS_SEC_CODE (SEC_CODE)
AS (
SELECT SEC_CODE
FROM IR_TB_NUR_SECTIONS
WHERE SEC_CODE = (select LOC.NURSING_SEC_CODE from mst_tb_location_mast loc where LOC.LOC_CODE = 20023)
UNION ALL
SELECT C1.SEC_CODE
FROM IR_TB_NUR_SECTIONS C1
INNER JOIN NUR_SECTIONS_SEC_CODE C2 ON C1.PREV_SEC = C2.SEC_CODE
)
SELECT *
FROM NUR_SECTIONS_SEC_CODE)
When executing it returns the below error:
"org.springframework.dao.InvalidDataAccessResourceUsageException:
could not extract ResultSet; SQL [n/a]; nested exception is
org.hibernate.exception.SQLGrammarException: could not extract
ResultSet"
What can I do about the above exception, please?
The "WITH" clause you are using is known as Common Table Expression (CTE) .I am pretty sure CTE is not supported by JPQL because if it is supported , no one will specially develop a library for supporting CTE query but only for Hibernate.
But you can switch to do use native SQL which should always work provided that your query can really be executed successfully against the database that you are using.

how to convert SQL select statement to LINQ

Hi i'm new to SQL and LINQ and i need to convert this sql statement to LINQ
select r.*,
(Select name From org_table where org_ID= r.org_ID )org
(Select name From Depart_table where Depart_ID= r.Depart_ID)depart
from reserve_table r
where name like '
try it this way:
var result = from r in reserve_table
where r.name.Contains("something")
select new {
org = (from o in org_table where o.Org_ID = r.Org_ID select o.name)
depart = (from d in Depart_table where d.Depart_ID = r.Depart_ID select d.name)
// add the rest
}

missing field in nested SQL statement in ms access 2010

The following MS Access 2010 query only outputs values for FirstName, HomePhone, and ClientNumber. It is not outputting any values for LastName.
Can anyone show me how to change it so that it outputs values for LastName also?
SELECT
ActiveCustomers.FirstName
, ActiveCustomers.LastName
, tblClientAddress.HomePhone
, ActiveCustomers.ClientNumber
FROM (
SELECT
Clients.ClientNumber
, Clients.FirstName
, Clients.LastName (
SELECT COUNT(ReferralDate) FROM IntakeTable
WHERE Clients.ClientNumber = IntakeTable.ClientNumber
AND Len(ReferralDate & '') > 0
) AS IntakeCount
, (
SELECT COUNT(ExitDate)
FROM ExitTable
WHERE Clients.ClientNumber = ExitTable.ClientNumber
AND Len(ExitDate & '') > 0
) AS ExitCount
FROM Clients
) AS ActiveCustomers
INNER JOIN tblClientAddress
ON ActiveCustomers.ClientNumber = tblClientAddress.ClientNumber
WHERE ActiveCustomers.IntakeCount > [ExitCount]
AND tblClientAddress.CurrentResidence = True;
You appear to be missing a comma after Clients.LastName. Try:
SELECT ActiveCustomers.FirstName, ActiveCustomers.LastName, tblClientAddress.HomePhone, ActiveCustomers.ClientNumber
FROM
(SELECT Clients.ClientNumber,
Clients.FirstName,
Clients.LastName,
(SELECT COUNT(ReferralDate) FROM IntakeTable WHERE Clients.ClientNumber = IntakeTable.ClientNumber AND Len(ReferralDate & '') > 0) AS IntakeCount,
(SELECT COUNT(ExitDate) FROM ExitTable WHERE Clients.ClientNumber = ExitTable.ClientNumber AND Len(ExitDate & '') > 0) AS ExitCount
FROM Clients) AS ActiveCustomers
INNER JOIN tblClientAddress ON ActiveCustomers.ClientNumber = tblClientAddress.ClientNumber
WHERE (((ActiveCustomers.IntakeCount)>[ExitCount]) AND
((tblClientAddress.CurrentResidence)=True));
EDIT:
It seems likely that:
You have a many-to-one (or one-to-many) relationship between Clients and tblClientAddress, and you have two records on the "many" side. If you are getting duplicate records, you could add a DISTINCT or a GROUP BY,
And/Or:
That the (SELECT COUNT( subqueries are somehow messing up their parent query, and need to be modified so that they can go into their parent query's FROM clause with an Inner Join, e.g.:
(SELECT ClientNumber, COUNT(ReferralDate) as IntakeCount FROM IntakeTable WHERE Len(ReferralDate & '') > 0 GROUP BY ClientNumber) AS qryIntakeCount

No Value Given For One or More Required Parameters, using sub-select queries

I'm trying to execute this select query in vb.net but it throws at me the No Value Given For One or More Required Parameters error. I keep re-checking my code but cannot see what is wrong.
SELECT statement to pull houseno, housename, street, productname, sequenceno and quantity using the DailyDelivery table, where the roundID = selectedID
Command.CommandText =
"SELECT customerid,
productid,
quantity,
(SELECT houseno
FROM customer
WHERE customer.customerid = dailydelivery.customerid) AS HouseNo,
(SELECT housename
FROM customer
WHERE customer.customerid = dailydelivery.customerid) AS HouseName,
(SELECT street
FROM customer
WHERE customer.customerid = dailydelivery.customerid) AS Street,
(SELECT sequenceno
FROM customer
WHERE customer.customerid = dailydelivery.customerid) AS SequenceNo,
(SELECT roundid
FROM customer
WHERE customer.customerid = dailydelivery.customerid) AS RoundID,
(SELECT productname
FROM product
WHERE product.productid = dailydelivery.productid) AS ProductName
FROM dailydelivery
WHERE issuedate = #TodaysDate
AND roundid = #SelectedID
ORDER BY sequenceno,
street,
houseno,
housename"
'Add parameter for command (TodaysDate being today's date)
`Command.Parameters.AddWithValue("#TodaysDate", Today.Date)`
'Add parameter for command (SelectedID being the current roundID)
`Command.Parameters.AddWithValue("#SelectedID", SelectedID)`
After this, command is called using a data adapter to fill a table in a dataset.
'Open connection to the database
dbConnection.Open()
'Set command's connection as dbconnection
Command.Connection = dbConnection
'Set the data adapter's select command as command
DataAdpt.SelectCommand = Command
'Fill ActualDelivery table in selectedDataset with the results of query, using the data adapter
DataAdpt.Fill(SelectedDataset, "ActualDelivery")
'Close connection to the database
dbConnection.Close()
The error is thrown on the DataAdapt.Fill line. I am using VB Express 2008 and Access 2013.
Probably I am wrong but I can't test the query.
I think you could refactor that query using JOIN
"SELECT d.customerid, d.productid, d.quantity, c.HouseNo, c.HouseName, " +
"c.Street, c.SequenceNo, c.RoundID, p.ProductName " +
"FROM (customer AS c INNER JOIN dailydelivery AS d ON c.customerid = d.customerid) " +
"INNER JOIN product AS p ON p.productid = d.productid " +
"WHERE d.issuedate = #TodaysDate AND c.roundid = #SelectedID " +
"ORDER BY c.sequenceno, c.street, c.houseno, c.housename"
Looking again at your query. Do you have a field named roundid on the dailydelivery table or is it the roundid of the customer table? As it stands now you need to have that field on the dailydelivery table otherwise it will be interpreted as the name of a parameter
You need to specify your parameters using just ? question marks, and make sure you add your parameters to the Parameters collection in the correct order. Or to just quote the documentation:
The OLE DB .NET Provider does not support named parameters for passing parameters to an SQL statement or a stored procedure called by an OleDbCommand when CommandType is set to Text. In this case, the question mark (?) placeholder must be used. For example:
SELECT * FROM Customers WHERE CustomerID = ?
Therefore, the order in which OleDbParameter objects are added to the OleDbParameterCollection must directly correspond to the position of the question mark placeholder for the parameter in the command text.

incorrect syntax near the keyword 'AS'

Why do i receive a syntax error as such: Incorrect syntax near the keyword 'AS'
I am using microsoft visual studio 2005 and sql server 2005
string strSql =
"SELECT a.MCode, a.NameOfModule, a.Mod_Abbreviation, dt.ModuleCode,
dt.Course, dt.Stage, dt.ModuleGrpFrom, dt.ModuleGrpTo, dt.GrpName,
dt.GrpType, dt.StaffID, dt.AcadYear, dt.AcadSemester,
dt.TotalHour, dt.WeeklyLectHr, dt.WeeklyPractHr, dt.WeeklyTutHr,
dt.ModuleLeader, 0 AS TotalTeach, '' AS ModuleGroups, '' AS ML, 0 AS L, 0 AS P, 0 AS T, 1 AS NofGrp, '' AS TotalTeachUnit" +
"FROM (SELECT * FROM
(SELECT a.ModuleCode, a.Course, a.Stage, a.ModuleGrpFrom,
a.ModuleGrpTo, a.GrpName, a.GrpType, a.StaffID, b.AcadYear,
b.AcadSemester, b.TotalHour, b.WeeklyLectHr, b.WeeklyPractHr,
b.WeeklyTutHr, b.ModuleLeader
FROM ModuleStrGrp a
LEFT JOIN ModuleStr b ON a.AcadYear = b.AcadYear
AND a.AcadSemester = b.AcadSemester
AND a.Course = b.Course
AND a.ModuleCode = b.ModuleCode) AS MSG
INNER JOIN Parameter Para ON MSG.Course = Para.Paracode2) AS dt
LEFT JOIN Module a ON dt.ModuleCode = a.MCode" +
"WHERE dt.AcadYear LIKE AcadYear AND dt.AcadSemester LIKE AcadSemester
AND dt.Course LIKE Course AND dt.Stage LIKE Stage AND dt.StaffID LIKE Staff
AND dt.SpecGrp LIKE Specialisation" +
"ORDER BY dt.ModuleCode, dt.GrpType";
Missing spaces.
Your code is creating the string
"... , '' AS TotalTeachUnitFROM (SELECT * ..."
Same goes for the other lines, they need spaces between them.
I won't answer your question, but I'll give you a strategy:
copy the contents of the strSql string to the clipboard, then to a query in SQL Management Studio, and run it there.
Then it will actually tell you which "AS" is causing the problem. Most likely it's a missing space or appostraphe or comma.
make "FROM ... as " FROM ...
right now it is ... AS TotalTeachUnitFROM ...
You are missing spaces.
"...a ON dt.ModuleCode = a.MCode" +
"FROM (SELECT * FROM ..."
results in
"...a ON dt.ModuleCode = a.MCodeFROM (SELECT * FROM ..."
^
space missing
Rather use # instead of +
string strSql = #"SELECT a.MCode, a.NameOfModule, a.Mod_Abbreviation, dt.ModuleCode, dt.Course, dt.Stage, dt.ModuleGrpFrom, dt.ModuleGrpTo, dt.GrpName, dt.GrpType, dt.StaffID, dt.AcadYear, dt.AcadSemester, dt.TotalHour, dt.WeeklyLectHr, dt.WeeklyPractHr, dt.WeeklyTutHr, dt.ModuleLeader, 0 AS TotalTeach, '' AS ModuleGroups, '' AS ML, 0 AS L, 0 AS P, 0 AS T, 1 AS NofGrp, '' AS TotalTeachUnit
FROM (SELECT * FROM (SELECT a.ModuleCode, a.Course, a.Stage, a.ModuleGrpFrom, a.ModuleGrpTo, a.GrpName, a.GrpType, a.StaffID, b.AcadYear, b.AcadSemester, b.TotalHour, b.WeeklyLectHr, b.WeeklyPractHr, b.WeeklyTutHr, b.ModuleLeader FROM ModuleStrGrp a LEFT JOIN ModuleStr b ON a.AcadYear = b.AcadYear AND a.AcadSemester = b.AcadSemester AND a.Course = b.Course AND a.ModuleCode = b.ModuleCode) AS MSG INNER JOIN Parameter Para ON MSG.Course = Para.Paracode2) AS dt LEFT JOIN Module a ON dt.ModuleCode = a.MCode
WHERE dt.AcadYear LIKE AcadYear AND dt.AcadSemester LIKE AcadSemester AND dt.Course LIKE Course AND dt.Stage LIKE Stage AND dt.StaffID LIKE Staff AND dt.SpecGrp LIKE Specialisation
ORDER BY dt.ModuleCode, dt.GrpType";