How can I create a datatable of my 3 select SQL statements - ado.net

I have a database with one table and I have 3 select SQL statement.
Those select items have different conditions. How can I merge the answer of this 3 SQL command?
I don't want to merge them, rows by rows to a data table. Is there any other way?
Some thing like this..
OleDbCommand cmd = new OleDbCommand("select top "+ cont0 +" * from (select * from db where tablenumber=0) order by ID ASC", mycon);
OleDbDataAdapter adapt=new OleDbDataAdapter(cmd);
DataTable dt = new DataTable();
DataTable dttemp = new DataTable();
adapt = new OleDbDataAdapter(cmd);
adapt.Fill(dt);
cmd = new OleDbCommand("select top "+ cont1 +" * from (select * from db where tablenumber=1) order by ID ASC", mycon);
adapt = new OleDbDataAdapter(cmd);
adapt.Fill(dttemp);
foreach (DataRow row in dttemp.Rows)
{
dt.Rows.Add(row.ItemArray);
}
if (cont2 != 0)
{
cmd = new OleDbCommand("select top " + cont2 + " * from (select * from db where tablenumber=2) order by ID ASC", mycon);
adapt = new OleDbDataAdapter(cmd);
dttemp = new DataTable();
adapt.Fill(dttemp);
foreach (DataRow row in dttemp.Rows)
{
dt.Rows.Add(row.ItemArray);
}
}
if (cont3 != 0)
{
cmd = new OleDbCommand("select top " + cont3 + " * from (select * from db where tablenumber=3) order by ID ASC", mycon);
adapt = new OleDbDataAdapter(cmd);
dttemp = new DataTable();
adapt.Fill(dttemp);
foreach (DataRow row in dttemp.Rows)
{
dt.Rows.Add(row.ItemArray);
}
}
if (cont4 != 0)
{
cmd = new OleDbCommand("select top " + cont4 + " * from (select * from db where tablenumber=4) order by ID ASC", mycon);
adapt = new OleDbDataAdapter(cmd);
dttemp = new DataTable();
adapt.Fill(dttemp);
foreach (DataRow row in dttemp.Rows)
{
dt.Rows.Add(row.ItemArray);
}
}
if (cont5 != 0)
{
cmd = new OleDbCommand("select top " + cont5 + " * from (select * from db where tablenumber=5) order by ID ASC", mycon);
adapt = new OleDbDataAdapter(cmd);
dttemp = new DataTable();
adapt.Fill(dttemp);
foreach (DataRow row in dttemp.Rows)
{
dt.Rows.Add(row.ItemArray);
}
}

You can merge them simply like this:
"select * from
(select *, row_number() over(partition by field order by id) as rn
from table1 where field in(0, 5, 9)) t
where rn <= " + cont
EDIT:
string command = "select * from ( select top "+ cont0 +" * from db where tablenumber=0 order by ID) t union all
select * from ( select top "+ cont1 +" * from db where tablenumber=1 order by ID) t";
if (cont2 != 0)
comand += " union all select * from ( select top " + cont2 + " * from db where tablenumber=2 order by ID) t";
if (cont3 != 0)
comand += " union all select * from ( select top " + cont3 + " * from db where tablenumber=3 order by ID) t";
....
OleDbCommand cmd = new OleDbCommand(command, mycon);
OleDbDataAdapter adapt=new OleDbDataAdapter(cmd);
DataTable dt = new DataTable();
....

Related

EntityFramework FromRawSql count query

Here is what i've done with entityframework.
I have a very complex query and i wanted to write it as a raw sql query this way:
var queryable1 = dbcontext.Set<MyViewModel>().FromSqlRaw(
" SELECT "
+ " field1,"
+ " field2,"
+ " <calculation1> as field3,
+ " (select count(*) from ...) as field4, "
...
+ " FROM mytable "
+ " LEFT JOIN xxxx "
+ " WHERE ...");
It works fine: I can query this way:
var queryable2 = queryable1.Where(....);
I have a problem when i try to make a count:
var count1 = queryable1.Count();
The count result is good but if i look the sql query executed on sql server i can see this:
SELECT COUNT(*) FROM
(SELECT field1, field2, <calculation1> as field3, ... FROM mytable WHERE ...)
This query is very slow. Is there a way to do something like that:
SELECT count(*) FROM mytable WHERE ...
Thanks

Convert an iteration to recursion

I have an iteration logic that returns a query like this :
val baseQuery = s"select agg_id from quality.QUALITY_AGGREGATOR where job_id = 123 and level ="
val reprocessDate ="2018-10-24"
for( i <- 0 to level){
var currLevelSubQuery=""
if (i==0 ){
currLevelSubQuery= baseQuery + s"$i and agg_value >= '${reprocessDate}'"
}
else{
currLevelSubQuery= baseQuery + s"$i and parent_agg_id in ( $prevLevelSubQuery )"
}
prevLevelSubQuery= currLevelSubQuery
finalQuery = finalQuery + currLevelSubQuery + (if (i<level) " union " else "")
}
It returns a query of this nature for level = 2.
SELECT agg_id
FROM quality.quality_aggregator
WHERE job_id = 123
AND level = 0
AND agg_value >= '2018-10-24'
UNION
SELECT agg_id
FROM quality.quality_aggregator
WHERE job_id = 123
AND level = 1
AND parent_agg_id IN (SELECT agg_id
FROM quality.quality_aggregator
WHERE job_id = 123
AND level = 0
AND agg_value >= '2018-10-24')
UNION
SELECT agg_id
FROM quality.quality_aggregator
WHERE job_id = 123
AND level = 2
AND parent_agg_id IN (SELECT agg_id
FROM quality.quality_aggregator
WHERE job_id = 123
AND level = 1
AND parent_agg_id IN
(SELECT agg_id
FROM quality.quality_aggregator
WHERE job_id = 123
AND level = 0
AND agg_value >=
'2018-10-24'))
I am trying to convert it into a recursive logic like this
val baseQuery = s"select agg_id from quality.QUALITY_AGGREGATOR where job_id = 123 and level ="
val finalQuery = getAggIdSQLGenerator(2,"2018-10-24")
def getAggIdSQLGenerator(level : Int, reprocessDate:String):String={
if (level == 0)
( baseQuery + s"$level and agg_value >= '${reprocessDate}'")
else
{
val subQuery=getAggIdSQLGenerator(level-1 ,reprocessDate)
baseQuery + s"$level and parent_agg_id in (" +subQuery +") union "+ subQuery
}
}
But this is not yielding correct results. What am I missing?
This isn't recursive but I think it's a smaller, cleaner, implementation of what you're after.
val baseQuery = ".... level="
val levelRE = "level=(\\d+)".r.unanchored
val reprocessDate ="2018-10-24"
val av = s" and agg_value >= '${reprocessDate}'"
val pai = " and parent_agg_id in "
val itrs = 3
val query = List.iterate(s"${baseQuery}0$av", itrs) { prevStr =>
val level = prevStr match {
case levelRE(n) => n.toInt + 1
case _ => 0
}
s"$baseQuery$level$pai($prevStr)"
}.mkString(" union ")
The issue is you have added union on every query and you have concatenated subquery 2 times.
This gives your expected output.
val baseQuery = s"select agg_id from quality.QUALITY_AGGREGATOR where job_id = 123 and level ="
val finalQuery = getAggIdSQLGenerator(2, "2018-10-24")
def getAggIdSQLGenerator(level: Int, reprocessDate: String): String = {
if (level == 0) {
baseQuery + s" $level and agg_value >= '${reprocessDate}'"
} else {
val subQuery = getAggIdSQLGenerator(level - 1, reprocessDate)
baseQuery + s" $level and parent_agg_id in (" + subQuery + ")"
}
}
println("UNION " + finalQuery)

Jpa Query Send part of Query as Parameter

i wan't query like this:
#Query(
nativeQuery = true,
value = "select vp.id , vp.identity, vp.vehicle_id, dt.i " +
"from vehicle_plate vp" +
" inner join (select max(vp2.id) as id, vp2.vehicle_id as vId from vehicle_plate vp2 group by vp2.vehicle_id) as vpg" +
" ON vp.id = vpg.id and vp.vehicle_id = vpg.vId" +
" cross join (values :dates ) dt(i)" +
"where vp.vehicle_id in (:vehicleIds)"
)
Page<Object[]> findAllJoinByDate(
#Param("dates") List<java.util.Date> dates,
#Param("vehicleIds") List<Integer> vehicleIds,
Pageable pageable
);
my problem is the part of query cross join (values :dates ) dt(i) and date parameter unknown by jpa.
should be same as
cross join (values ('2019-10-08') , ('2019-09-07') ) dt(i)
is there solution for this?

Count using native SQL in JPA Data Spring returns 0

I have a problem with one query/interface:
#Query(value = "SELECT count(1) FROM que_table que " +
"WHERE que.CREATED_DATE >= (SELECT CREATED_DATE " +
" FROM que_table " +
" WHERE id = :selectedId " +
" ORDER BY CREATED_DATE DESC LIMIT 1) " +
"AND que.QUEUE_STATUS in (:queueStatuses)", nativeQuery = true)
Long countCurrentPosition(#Param("selectedId ") String selectedId , #Param("queueStatuses") Set<QueueStatus> queueStatuses);
I connect to MySQL using spring-data-JPA.
When I run this query on console it's working perfectly.
What is wrong here?
Thanks in advance.
use string name of QueueStatus enum :
#Query(value = "SELECT count(1) FROM que_table que " +
"WHERE que.CREATED_DATE >= (SELECT CREATED_DATE " +
" FROM que_table " +
" WHERE id = :selectedId " +
" ORDER BY CREATED_DATE DESC LIMIT 1) " +
"AND que.QUEUE_STATUS in (:queueStatuses)", nativeQuery = true)
Long countCurrentPosition(#Param("selectedenter code hereId ") String selectedId , #Param("queueStatuses") Set<String> queueStatuses);

Selecting users,groups and site from alfresco database

I would like to select users,in which groups they belong to, and their sites. I want it with a single postgre sql query.
I've found these queries, but i want them combined with join if possible.
select * from alf_permission
select * from ALF_AUTHORITY
select * from ALF_CHILD_ASSOC where CHILD_NODE_NAME like ‘group%’
select * from ALF_CHILD_ASSOC where QNAME_LOCALNAME like ‘GROUP%’
select
node_id,
string_agg(string_value, ',')
from (
select
node_id,
qname_id,
(select local_name from alf_qname where id = qname_id) as qname_type,
string_value
from alf_node_properties
where node_id in (
select id from alf_node
where type_qname_id = (
select id from alf_qname where local_name = 'person'
)
and qname_id in (
select id
from alf_qname
where local_name in (
'username',
'firstName',
'lastName',
'email'
)
)
)
) alf_users
group by node_id;
I would advise to create webscript possibly in Java that will do this fast and efficient!
I found a solution!
I put the script in Company Home > Data Dictionary > Web Scripts > org > alfresco > test
As you can see i created the "test" folder in "alfresco" folder, and in it i put these three files.
hello.get.html.ftl file
<table border>
<tr>
<th>Username</th>
<th>Groups</th>
<th>Sites</th>
</tr>
<#list test as child>
<tr>
<td>${child['username']}</td>
<td>${child['groups']}</td>
<td>${child['sites']}</td>
</tr>
</#list>
</table>
hello.get.desc.xml
<webscript>
<shortname>Hello</shortname>
<description>Polite greeting</description>
<url>/test/hello</url>
<authentication>user</authentication>
</webscript>
hello.get.js
var gens = search.luceneSearch("TYPE:\"{http://www.alfresco.org/model/content/1.0}person\"");
var a = [];
for (var i=0; i<gens.length;i++) {
var username = gens[i].properties["cm:userName"];
var b = [];
var groups = people.getContainerGroups(gens[i]);
for(var j=0; j<groups.length; j++) {
b.push(groups[j].properties['authorityDisplayName']);
}
var sites = siteService.listUserSites(username);
var g=[]
for(var j=0; j<sites.length; j++) {
g.push(sites[j]['shortName']);
}
//a.push('\n\n\n'+username+'\groups--> '+ b.join(', ') + '\nsites--> '+g.join(', '));
a.push({
'username' : username,
'groups' : b.join(', '),
'sites' : g.join(', ')
})
}
model.test = a;
you can access the result in your_domain_name/alfresco/service/test/hello
Try this query to get persons and groups
select
ca.id,
ca.parent_node_id,
ca.child_node_id,
ca.qname_localname,
np.string_value
from alf_child_assoc as ca
join alf_node as child on child.id = ca.child_node_id
join alf_node as parent on parent.id = ca.parent_node_id
join alf_qname as q1 on q1.id = parent.type_qname_id
join alf_qname as q2 on q2.id = child.type_qname_id
join alf_node_properties as np on np.node_id = parent.id
where q1.local_name = 'authorityContainer'
and q2.local_name = 'person'
and np.qname_id = (select id from alf_qname where local_name =
'authorityDisplayName')
order by ca.qname_localname;`