How Can I write query in Subsonic for Subqueires - subsonic

How can I do the following query in subsonic 2.2
select Table1.Id, Table1.Name, Table1.Age from Table1
where Table1.Id =
(
select Max(T.Id) from Table1 T
Where T.Age = 20
)
Can one can provide me with example.
Thanks.
nRk

Subsonic 2.2 can do sub-queries:
As Adam suggested, editted and improved example using In, this works for me:
SubSonic.Select s = new SubSonic.Select(SSDAL.Customer.CustomerIDColumn, SSDAL.Customer.NameColumn);
SubSonic.Aggregate a = new SubSonic.Aggregate(SSDAL.Customer.CustomerIDColumn, SubSonic.AggregateFunction.Max);
SSDAL.CustomerCollection COL = new SSDAL.CustomerCollection();
SubSonic.Select sq = new SubSonic.Select("LastCustomerId");
sq.Aggregates.Add(a);
sq.From(Tables.Customer);
a.Alias = "LastCustomerId";
s.From(Tables.Customer);
s.Where(SSDAL.Customer.CustomerIDColumn).In(sq);
COL = s.ExecuteAsCollection<SSDAL.CustomerCollection>();
;
This code produces the following SQL:
SELECT [dbo].[Customer].[CustomerID], [dbo].[Customer].[Name]
FROM [dbo].[Customer]
WHERE [dbo].[Customer].[CustomerID] IN (SELECT MAX([dbo].[Customer].[CustomerID]) AS 'LastCustomerId'
FROM [dbo].[Customer])

Adam may be onto something but it looks a little ugly. Here is an example that is a bit more readable that returns an IDataReader
new SubSonic.Select(Table1.IdColumn,Table1.NameColumn,Table1.AgeColumn)
.From(Table1.Schema)
.Where(Table1.IdColumn).In(new SubSonic.Select(Aggregate.Max(Table1.IdColumn)).From(Table1.Schema))
.ExecuteReader();

As far as I know there is no support for subqueries in SubSonic. You'll need to put the query in a sproc and use the generated SPs.SprocName() method.
EDIT: I was wrong, see other answer below.

Related

Kentico 10 ObjectQuery join multiple tables

I am basically trying to run a query that gives me all the Users that have purchased a product with a particular SKU. Essentially this SQL here:
SELECT u.FirstName, u.LastName, u.Email
FROM COM_OrderItem oi INNER JOIN COM_Order o ON oi.OrderItemOrderID = o.OrderID
INNER JOIN COM_Customer c ON o.OrderCustomerID = c.CustomerID
INNER JOIN CMS_User u ON c.CustomerUserID = u.UserID
WHERE oi.OrderItemSKUID = 1013
I was trying to use the ObjectQuery API to try and achieve this but have no idea how to do this. The documentation here does not cover the specific type of scenario I am looking for. I came up with this just to try and see if it works but I don't get the three columns I am after in the result:
var test = OrderItemInfoProvider
.GetOrderItems()
.Source(orderItems => orderItems.Join<OrderInfo>("OrderItemOrderID", "OrderID"))
.Source(orders => orders.Join<CustomerInfo>("OrderCustomerID", "CustomerID"))
.Source(customers => customers.Join<UserInfo>("CustomerUserID", "UserID"))
.WhereEquals("OrderItemSKUID", 1013).Columns("FirstName", "LastName", "Email").Result;
I know this is definitely wrong and I would like to know the right way to achieve this. Perhaps using ObjectQuery is not the right approach here or maybe I can somehow just use raw SQL. I simply don't know enough about Kentico to understand the best approach here.
Actually, the ObjectQuery you created is correct. I tested it and it is providing the correct results. Are you sure that there are indeed orders in the system, which contain a product with SKUID 1013 (you can check that in the COM_OrderItem database table)?
Also, how are you accessing the results? Iterating through the results should look like this:
foreach (DataRow row in test.Tables[0].Rows)
{
string firstName = ValidationHelper.GetString(row["FirstName"], "");
string lastName = ValidationHelper.GetString(row["LastName"], "");
string email = ValidationHelper.GetString(row["Email"], "");
}

Python Simple Salesforce Select AS Not Working

I'm trying the standard SELECT ... AS call to rename a column in query output with the Python Salesforce API and it's throwing following error:
... unexpected token: 'AS'", 'errorCode': 'MALFORMED_QUERY'}
So far most native language calls from SOQL have been working in the API and it seems, from here, that SELECT ... AS is valid SOQL.
Query outline:
from simple_salesforce import Salesforce
sf = Salesforce(username=myusername, password=mypassword, security_token=mytoken)
query = "select closedate as Date from opportunity"
query_list = sf.query_all(query)['records']
edit
error remains even after putting the new column name within quotes as advised in above link:
query = "select closedate as \"Date\" from Opportunity"
Thanks
As Terminus mentioned, SOQL field aliasing is not possible in SOQL in most contexts, including yours. The only case in which I have seen aliasing working in SOQL is in aggregate queries. For example, in apex you could write:
AggregateResult myResult = [SELECT count(Id) SpecialName FROM Contact];
system.debug(myResult);
and receive the result:
DEBUG|AggregateResult:{SpecialName=1630}
In python via simple-salesforce it would look like this:
sf.query_all('SELECT count(Id) SpecialName FROM Contact')
with the result:
OrderedDict([('totalSize', 1),
('done', True),
('records',
[OrderedDict([('attributes',
OrderedDict([('type', 'AggregateResult')])),
('SpecialName', 6587)])])])
Please mark as answered if this answer your question.
The syntax seems to be incorrect.
Try query = "select closedate <insert alias> from Opportunity" according to the alias notation documented here : https://developer.salesforce.com/docs/atlas.en-us.soql_sosl.meta/soql_sosl/sforce_api_calls_soql_alias.htm

How do you add elements to a set with DataStax QueryBuilder?

I have a table whose column types are
text, bigint, set<text>
I'm trying to update a single row and add an element to the set using QueryBuilder.
The code that overwrites the existing set looks like this (note this is scala):
val query = QueryBuilder.update("twitter", "tweets")
.`with`(QueryBuilder.set("sinceid", update.sinceID))
.and(QueryBuilder.set("tweets", setAsJavaSet(update.tweets)))
.where(QueryBuilder.eq("handle", update.handle))
I was able to find the actual CQL for adding an element to a set which is:
UPDATE users
SET emails = emails + {'fb#friendsofmordor.org'} WHERE user_id = 'frodo';
But could not find an example using QueryBuilder.
Based off of the CQL I also tried:
.and(QueryBuilder.set("tweets", "tweets"+{setAsJavaSet(update.tweets)}))
But it did not work. Thanks in advance
Use add (add one element at a time) or addAll (more than one any number of element at a time) method to add to a set.
To extend Ananth's answer:
QueryBuilder.add does not support BindMarker. To use BindMarker while adding in set, it is required to use QueryBuilder.addAll only.*
*Just a note, Collections.singleton may come in handy in this regard.
Using #Ananth and #sazzad answers, the code below works:
Session cassandraSession;
UUID uuid;
Long value;
Statement queryAddToSet = QueryBuilder
.update("tableName")
.with(QueryBuilder.addAll("setFieldName", QueryBuilder.bindMarker()))
.where(QueryBuilder.eq("whereFieldName", QueryBuilder.bindMarker()));
PreparedStatement preparedQuery = cassandraSession.prepare(queryAddToSet);
BoundStatement boundQuery = preparedQuery.bind();
boundQuery
.setUUID("whereFieldName", uuid)
.setSet("setFieldName", Collections.singleton(value));
session.execute(boundQuery);

Nhibernate linq where clause with boolean value

If I try to add a where clause, containing a lambda filter on a boolean field, to a nhibernate linq query, the filter seems to be ignored:
var result = Session.Linq().Where(x=> x.Approved);
Session is an iSession and Newspaper is a simple object with the fields NewspaperId int, Name - varchar(50) and Approved - bit.
When I run this the following sql is generated:
SELECT this_.NewspaperId as Newspape1_33_0_, this_.Name as Name33_0_, this_.Approved as Approved33_0_, FROM Newspapers this_
it seems to ignore the lambda if it is for a boolean field.
It works fine for the name field, ie:
var result = Session.Linq().Where(x=> x.Name == "The Times");
results in:
exec sp_executesql N'SELECT this_.NewspaperId as Newspape1_33_0_, this_.Name as Name33_0_, this_.Approved as Approved33_0_ FROM Newspapers this_ WHERE this_.Name = #p0',N'#p0 nvarchar(9)',#p0=N'The Times'
Anybody know why I can't query on a boolean value?
Any help is greatly appreciated
I am using NHibernate 2.1 with linq
It's been a while so you've probably got your answer somewhere else a long time ago. But to answer your question: I can't see a reason why this wouldn't work. Actually I've tried it out in both NH2.1.2 and NH3.0.0. It works in both (verified by looking at the query with SQL Profiler). So it would be interesting to see the mapping you used, perhapse there's something wrong there.

SubSonic Collection Top 1

Is there way in next piece of code to only get the first record?
Dal.TreeHtmlExportsCollection treeHtmlExportsCollection =
new Dal.TreeHtmlExportsCollection().Where(Dal.TreeHtmlExports.Columns.TreeId, treeId).
OrderByDesc(Dal.TreeHtmlExports.Columns.DateCreated).Load();
You can do this using the Query tool like so: (requires SubSonic 2.1)
var query = new Select()
.Top("1")
.From(TreeHtmlExports.Schema)
.Where(TreeHtmlExports.Columns.TreeId).IsEqualTo(treeId)
.OrderDesc(TreeHtmlExports.Columns.DateCreated);
treeHtmlExportCollection = query.ExecuteAsCollection<TreeHtmlExportsCollection>();
Hope that helps!

Resources