Query a CRM SavedQuery via SQL SSMS - dynamics-crm

In SSMS I can go to our CRM database and run these:
SELECT *
FROM SavedQueryBase
WHERE [name] LIKE 'customer%';
SELECT *
FROM SavedQuery
WHERE [name] LIKE 'customer%';
Which both return information on the CRM View.
My Question is - is it possible to actually execute the view in SSMS? In CRM I get 4,000+ records in the View and I need to see these same records in SSMS. I can't seem to find out how to do it.

Ok ... found it, but posting it here for the next poor person who also can't figure it out.
You need to look at the FetchXML field which comes back as a result of the queries I posted in the Question.
Then you need to decipher those to build your query. All the info is in the XML, the base table, the fields selected, ordering etc ... Just takes some effort, and of course if the user changes the view, you'll need to redo it.

Related

oracle forms 6i frm-40301 query caused no records to be retrieved

I have created sales master and sales detail (master/detail) relationship form.
I have entered record and saved it ...
Through another form, i hv updated few fields of sales_master table .. see below example
During data entry - Like ... Sal_OrdStatus = 'Open' and CashRcvd_Status='P'
Updating these fields through payment form Sal_OrdStatus = 'Closed' and CashRcvd_Status='R'
After this, when I am entering/execute those records where both fields are updated
then see below error even record is available in the database/table
frm-40301 query caused no records to be retrieved, re-enter
enter image description here
Please advise solution/ guideline
Thanks
Javed Akram
Querying data block won't return anything if there are no rows in the table at all, or if condition you set prevents any rows to be retrieved.
As some rows obviously exist (you updated them, not deleted), then it is the latter.
Use get_block_property built in and its last_query property (you can try default_where as well) to see which query was really executed; you'll see the where clause, and that should help you find the culprit. Once you know it, you'll be able to fix it.

Loading records into Dynamics 365 through ADF

I'm using the Dynamics connector in Azure Data Factory.
TLDR
Does this connector support loading child records which need a parent record key passed in? For example if I want to create a contact and attach it to a parent account, I upsert a record with a null contactid, a valid parentcustomerid GUID and set parentcustomeridtype to 1 (or 2) but I get an error.
Long Story
I'm successfully connecting to Dynamics 365 and extracting data (for example, the lead table) into a SQL Server table
To test that I can transfer data the other way, I am simply loading the data back from the lead table into the lead entity in Dynamics.
I'm getting this error:
Failure happened on 'Sink' side. ErrorCode=DynamicsMissingTargetForMultiTargetLookupField,'Type=Microsoft.DataTransfer.Common.Shared.HybridDeliveryException,Message=,Source=,''Type=Microsoft.DataTransfer.Common.Shared.HybridDeliveryException,Message=Cannot find the target column for multi-target lookup field: 'ownerid'.
As a test I removed ownerid from the list of source columns it loads OK.
This is obviously a foreign key value.
It raises two questions for me:
Specifically with regards to the error message: If I knew which lookup it needed to use, how can I specify which lookup table it should validate against? There's no settings in the ADF connector to allow me to do this.
This is obviously a foreign key value. If I only had the name (or business key) for this row, how can I easily lookup the foreign key value?
How is this normally done through other API's, i.e. the web API?
Is there an XRMToolbox addin that would help clarify?
I've also read some posts that imply that you can send pre-connected data in an XML document so perhaps that would help also.
EDIT 1
I realised that the lead.ownertypeid field in my source dataset is NULL (that's what was exported). It's also NULL if I browse it in various Xrmtoolbox tools. I tried hard coding it to systemuser (which is what it actually is in the owner table against the actual owner record) but I still get the same error.
I also notice there's a record with the same PK value in systemuser table
So the same record is in two tables, but how do I tell the dynamics connector which one to use? and why does it even care?
EDIT 2
I was getting a similar message for msauto_testdrive for customerid.
I excluded all records with customerid=null, and got the same error.
EDIT 2
This link appears to indicate that I need to set customeridtype to 1 (Account) or 2 (Contact). I did so, but still got the same error.
Also I believe I have the same issue as this guy.
Maybe the ADF connector suffers from the same problem.
At the time of writing, #Arun Vinoth was 100% correct. However shortly afterwards there was a documentation update (in response to a GitHub I raised) that explained how to do it.
I'll document how I did it here.
To populate a contact with against a parent account, you need the parent accounts GUID. Then you prepare a dataset like this:
SELECT
-- a NULL contactid means this is a new record
CAST(NULL as uniqueidentifier) as contactid,
-- the GUID of the parent account
CAST('A7070AE2-D7A6-EA11-A812-000D3A79983B' as uniqueidentifier) parentcustomerid,
-- customer id is an account
'account' [parentcustomerid#EntityReference],
'Joe' as firstname,
'Bloggs' lastname,
Now you can apply the normal automapping approach in ADF.
Now you can select from this dataset and load into contact. You can apply the usual automapping approach, this is: create datasets without schemas. Perform a copy activity without mapping columns
This is the ADF limitation with respect to CDS polymorphic lookups like Customer and Owner. Upvote this ADF idea
Workaround is to use two temporary source lookup fields (owner team and user in case of owner, account and contact in case of customer) and with parallel branch in a MS Flow to solve this issue. Read more, also you can download the Flow sample to use.
First, create two temporary lookup fields on the entity that you wish to import Customer lookup data into it, to both the Account and Contact entities respectively
Within your ADF pipeline flow, you will then need to map the GUID values for your Account and Contact fields to the respective lookup fields created above. The simplest way of doing this is to have two separate columns within your source dataset – one containing Account GUID’s to map and the other, Contact.
Then, finally, you can put together a Microsoft Flow that then performs the appropriate mapping from the temporary fields to the Customer lookup field. First, define the trigger point for when your affected Entity record is created (in this case, Contact) and add on some parallel branches to check for values in either of these two temporary lookup fields
Then, if either of these conditions is hit, set up an Update record task to perform a single field update, as indicated below if the ADF Account Lookup field has data within it

Redshift View keeps reverting to previous definition

I created a view in Redshift that unions two queries, and it works great. We've thought of a third query that would be worthwhile to add in. eg
CREATE VIEW stem_alumni as
SELECT name, email
FROM students
WHERE graduated < 2019 AND major = 'Engineering'
UNION
SELECT name, email
FROM alumni
WHERE current_employer = 'Google'
The problem is when I try to add a third query in
UNION
SELECT name, email
FROM professors
WHERE department = 'Engineering'
it'll persist for maybe an hour, but then revert to just the original query.
I've run CREATE OR REPLACE VIEW... and dropping/recreate and get the same result.
How do I get an updated view definition to persist?
Adding more context
I created the view using DBeaver, a local SQL client using my specific Redshift credentials. The view is called by Periscope, our cloud-based BI tool using shared credentials. Querying the view in Periscope or separate DBeaver windows will eventually revert the view to its original definition.
Redshift shouldn't have a 'memory' of the view's prior DDL that it could revert to. I'm inclined to agree with the comments that something else is overwriting the updates to the view's DDL after you have committed them.
You should be able to see if something is overwriting the view, by querying the stl_query table:
SELECT q.starttime
, u.usename
, q.querytxt
FROM pg_user u
JOIN stl_query q ON u.usesysid = q.userid
WHERE POSITION('<view_name>' IN q.querytxt) > 0
ORDER BY q.starttime DESC
;
This table only contains recent query information (2-5 days according to the Redshift Documentation), so if you haven't experienced this behavior from the view within that timescale, you may need to force it to occur again in order to troubleshoot who/what is altering the DDL.
Additionally, if the view is being overwritten by a user other than yourself, you will need to query stl_query using a super user account (by default, non-super users will only be able to view information for queries that they themselves have executed).

Display Distinct values in LightSwitch browse screen

i have one browse screen which is fetching value from one entity(Attached to SQL datasource),
the entity will look like the below snapshot.
So in the browse screen its coming with all row values (1,2,3 and 4) even though i removed the Role field from the screen. I want to display the distinct Emp ID, Name, Age. Please give me some suggestion.
The question tags Lightswitch 2013 and 2012 so it's not clear what the OP is using. Views handling in Lightswitch before VS2013 Update 2 can be a little more challenging (particularly around the definition of key fields) so the other possibility is to use a WCF-RIA service to reshape the data. Having a WCF-RIA service ready to go always comes in handy eventually, even if there are annoying limitations and quirks there as well.
The exact steps depend slightly on what version of VS you are using:
The canonical article by Eric Erhardt - http://blogs.msdn.com/b/lightswitch/archive/2011/04/08/how-do-i-display-a-chart-built-on-aggregated-data-eric-erhardt.aspx
An up to date version for VS2013 - http://lightswitchhelpwebsite.com/Blog/tabid/61/EntryId/2226/Creating-a-WCF-RIA-Service-for-Visual-Studio-2013.aspx
Happy to help further with specific queries if you decide to go down the WCF-RIA route.
Phil
If you don't have the option of driving your Browse screen from your employee table I'd suggest creating a SQL view similar to the following: -
CREATE VIEW [dbo].[EmployeeView]
AS
SELECT DISTINCT
EmpId,
Name,
Age,
Role
FROM
dbo.YourTable
You can then attach to the view in LightSwitch and base the Browse screen on the attached view.
However, please bear in mind that you will only be able to view and not update the information as this type of view uses the DISTINCT clause.
The following blog post provides some basic details of using views in LightSwitch: -
Attaching to SQL Views

Very slow search of a simple entity relationship

We use CRM 4.0 at our institution and have no plans to upgrade presently as we've spend the last year and a half customising and extending the CRM to work with our processes.
A tiny part of model is a simply hierarchy, we have a group of learning rooms that has a one-to-many relationship with another entity that describes the courses available for that learning room.
Another entity has a list of all potential and enrolled students who have expressed an interest in whichever course.
That bit's all straightforward and works pretty well and is modelled into 3 custom entities.
Now, we've got an Admin application that reads the rooms and then wants to show the courses for that room, but only where there are enrolled students.
In SQL this is simplified to:
SELECT DISTINCT r.CourseName, r.OtherInformation
FROM Rooms r
INNER JOIN Students S
ON S.CourseId = r.CourseId
WHERE r.RoomId = #RoomId
And this indeed is very close to the eventual SQL that CRM generates.
We use a Crm QueryEntity, a Filter and a LinkEntity to represent this same structure.
The problem now is that the CRM normalizes the a customize entity into a Base Table which has the standard CRM entity data that all share, and then an ExtensionBase Table which has our customisations. To Give a flattened access to this, it creates a view that merges both tables.
This view is what is used by the Generated SQL.
Now the base tables have indices but the view doesn't.
The problem we have is that all we want to do is return Courses where the inner join is satisfied, it's enough to prove there are entries and CRM makes it SELECT DISTINCT, so we only get one item back for Room.
At first this worked perfectly well, but now we have thousands of queries, it takes well over 30 seconds and of course causes a timeout in anything but SMS.
I'm given to believe that we can create and alter indices on tables in CRM and that's not considered to be an unsupported modification; but what about Views ?
I know that if we alter an entity then its views are recreated, which would of course make us redo our indices when this happens.
Is there any way to hint to CRM4.0 that we want a specific index in place ?
Another source recommends that where you get problems like this, then it's best to bring data closer together, but this isn't something I'd feel comfortable in trying to engineer into our solution.
I had considered putting a new entity in that only has RoomId, CourseId and Enrolment Count in to it, but that smacks of being incredibly hacky too; After all, an index would resolve the need to duplicate this data and have some kind of trigger that updates the data after every student operation.
Lastly, whilst I know we're stuck on CRM4 at the moment, is this the kind of thing that we could expect to have resolved in CRM2011 ? It would certainly add more weight to the upgrading this 5 year old product argument.
Since views are "dynamic" (conceptually, their contents are generated on-the-fly from the base tables every time they are used), they typically can't be indexed. However, SQL Server does support something called an "indexed view". You need to create a unique clustered index on the view, and the query analyzer should be able to use it to speed up your join.
Someone asked a similar question here and I see no conclusive answer. The cited concerns from Microsoft are Referential Integrity (a non-issue here) and Upgrade complications. You mention the unsupported option of adding the view and managing it over upgrades and entity changes. That is an option, as unsupported and hackish as it is, it should work.
FetchXml does have aggregation but the query execution plans still uses the views: here is the SQL generated from a simple select count from incident:
'select
top 5000 COUNT(*) as "rowcount"
, MAX("__AggLimitExceededFlag__") as "__AggregateLimitExceeded__" from (select top 50001 case when ROW_NUMBER() over(order by (SELECT 1)) > 50000 then 1 else 0 end as "__AggLimitExceededFlag__" from Incident as "incident0" ...
I dont see a supported solution for your problem.
If you are building an outside admin app and you are hosting CRM 4 on-premise you could go directly to the database for your query bypassing the CRM API. Not supported but would allow you to solve the problem.
I'm going to add this as a potential answer although I don't believe its a sustainable or indeed valid long-term solution.
After analysing the indexes that CRM had defined automatically, I realised that selecting more information in my query would be enough to fulfil the column requirements of an Index and now the query runs in less then a second.

Resources