Querying res column of RESOURCE_VIEW
Mark ,
i want to create a resource on the repository, and then create views based on xpath, update some tables and then delete the resource.
Now when i place the xml file in a xmltpye column every thing works fine. But it seems to be bit tricky wheni want to query from RES column. Might be problem with multiple namespace being used for each resource, not sure about it.
Now till here i am able to query successfully as you see the output.
SQL> select
2 extract(res, '/Resource/Contents').getclobval()
3 from resource_view
4 where any_path like '/public/labor/sequencedata.xml'
5 /
<Contents xmlns="http://xmlns.oracle.com/xdb/XDBResource.xsd">
<SequenceData>
<Header>
<id>285062</id>
<TemplateName>1 dup</TemplateName>
<TemplateVersion>1</TemplateVersion>
<CreUser>AJB2KOR</CreUser>
<CreDate>02-SEP-05</CreDate>
</Header>
<Variables>
<SetPhaseVariables/>
<MeasPhaseVariables>
<MeasPhaseVariable>
<Name>TimeStamp</Name>
<Unit>Sec</Unit>
</MeasPhaseVariable>
</MeasPhaseVariables>
<MonitoredVariables>
<MonitoredVariable>
<Name>Svar b</Name>
<Unit>b</Unit>
</MonitoredVariable>
<MonitoredVariable>
<Name>Svar c</Name>
<Unit>c</Unit>
</MonitoredVariable>
</MonitoredVariables>
</Variables>
<LoadPoint LevelNumber="1" id="114103" Description="LOADPOINT: (werwrwrw)">
<LoopCount InnerLoop="1" OuterLoop="1">
<MonitoredVariables/>
<SetPhase>
<MonitoredVariables/>
<SetPhaseVariables/>
</SetPhase>
<WaitPhase>
<WaitingTime>0</WaitingTime>
<MonitoredVariables/>
</WaitPhase>
<MeasPhase>
<MeasPhaseLoopRun/>
<Manual>N</Manual>
<MeasPhaseVariables/>
</MeasPhase>
</LoopCount>
</LoadPoint>
</SequenceData>
</Contents>
now when i want to navigate one more level below to the SequenceData it does not work.
SQL> select
2 extract(res, '/Resource/Contents/SequenceData').getclobval()
3 from resource_view
4 where any_path like '/public/labor/sequencedata.xml'
5 /
SQL>
Hi Raghu
You were on the right lines.. See below
SQL> set long 1000 pages 0
SQL> --
SQL> var targetPath varchar2(256)
SQL> --
SQL> begin
2 :targetPath := '/public/testcase.xml';
3 end;
4 /
PL/SQL procedure successfully completed.
SQL> declare
2 res boolean;
3 contents xmltype := xmltype(
4 '<SequenceData>
5 <Header>
6 <id>285062</id>
7 <TemplateName>1 dup</TemplateName>
8 <TemplateVersion>1</TemplateVersion>
9 <CreUser>AJB2KOR</CreUser>
10 <CreDate>02-SEP-05</CreDate>
11 </Header>
12 <Variables>
13 <SetPhaseVariables/>
14 <MeasPhaseVariables>
15 <MeasPhaseVariable>
16 <Name>TimeStamp</Name>
17 <Unit>Sec</Unit>
18 </MeasPhaseVariable>
19 </MeasPhaseVariables>
20 <MonitoredVariables>
21 <MonitoredVariable>
22 <Name>Svar b</Name>
23 <Unit>b</Unit>
24 </MonitoredVariable>
25 <MonitoredVariable>
26 <Name>Svar c</Name>
27 <Unit>c</Unit>
28 </MonitoredVariable>
29 </MonitoredVariables>
30 </Variables>
31 <LoadPoint LevelNumber="1" id="114103" Description="LOADPOINT: (werwrwrw)">
32 <LoopCount InnerLoop="1" OuterLoop="1">
33 <MonitoredVariables/>
34 <SetPhase>
35 <MonitoredVariables/>
36 <SetPhaseVariables/>
37 </SetPhase>
38 <WaitPhase>
39 <WaitingTime>0</WaitingTime>
40 <MonitoredVariables/>
41 </WaitPhase>
42 <MeasPhase>
43 <MeasPhaseLoopRun/>
44 <Manual>N</Manual>
45 <MeasPhaseVariables/>
46 </MeasPhase>
47 </LoopCount>
48 </LoadPoint>
49 </SequenceData>');
50 begin
51 if (dbms_xdb.existsResource(:targetPath)) then
52 dbms_xdb.deleteResource(:targetPath);
53 end if;
54 res := dbms_xdb.createResource(:targetPath,contents);
55 end;
56 /
PL/SQL procedure successfully completed.
SQL> commit;
Commit complete.
SQL> /
Commit complete.
SQL> select extract(res, '/Resource/Contents', 'xmlns="http://xmlns.oracle.com/xdb/XDBResource.xsd"').getclobval()
2 from resource_view
3 where equals_path(res, :targetPath) = 1
4 /
<Contents xmlns="http://xmlns.oracle.com/xdb/XDBResource.xsd"><SequenceData xmln
s=""><Header><id>285062</id><TemplateName>1 dup</TemplateName><TemplateVersion>1
</TemplateVersion><CreUser>AJB2KOR</CreUser><CreDate>02-SEP-05</CreDate></Header
<Variables><SetPhaseVariables/><MeasPhaseVariables><MeasPhaseVariable><Name>TimeStamp</Name><Unit>Sec</Unit></MeasPhaseVariable></MeasPhaseVariables><Monitored
Variables><MonitoredVariable><Name>Svar b</Name><Unit>b</Unit></MonitoredVariabl
e><MonitoredVariable><Name>Svar c</Name><Unit>c</Unit></MonitoredVariable></Moni
toredVariables></Variables><LoadPoint LevelNumber="1" id="114103" Description="L
OADPOINT: (werwrwrw)"><LoopCount InnerLoop="1" OuterLoop="1"><MonitoredVariables
/><SetPhase><MonitoredVariables/><SetPhaseVariables/></SetPhase><WaitPhase><Wait
ingTime>0</WaitingTime><MonitoredVariables/></WaitPhase><MeasPhase><MeasPhaseLoo
pRun/><Manual>N</Manual><MeasPhaseVariables/></MeasPhase></LoopCount></LoadPoint
</SequenceData></Contents>
SQL> select extract(res, '/r:Resource/r:Contents/SequenceData', 'xmlns:r="http://xmlns.oracle.com/xdb/XDBResource.xsd"').getclobval()
2 from resource_view
3 where equals_path(res, :targetPath) = 1
4 /
<SequenceData><Header><id>285062</id><TemplateName>1 dup</TemplateName><Template
Version>1</TemplateVersion><CreUser>AJB2KOR</CreUser><CreDate>02-SEP-05</CreDate
</Header><Variables><SetPhaseVariables/><MeasPhaseVariables><MeasPhaseVariable><Name>TimeStamp</Name><Unit>Sec</Unit></MeasPhaseVariable></MeasPhaseVariables><
MonitoredVariables><MonitoredVariable><Name>Svar b</Name><Unit>b</Unit></Monitor
edVariable><MonitoredVariable><Name>Svar c</Name><Unit>c</Unit></MonitoredVariab
le></MonitoredVariables></Variables><LoadPoint LevelNumber="1" id="114103" Descr
iption="LOADPOINT: (werwrwrw)"><LoopCount InnerLoop="1" OuterLoop="1"><Monitored
Variables/><SetPhase><MonitoredVariables/><SetPhaseVariables/></SetPhase><WaitPh
ase><WaitingTime>0</WaitingTime><MonitoredVariables/></WaitPhase><MeasPhase><Mea
sPhaseLoopRun/><Manual>N</Manual><MeasPhaseVariables/></MeasPhase></LoopCount></
LoadPoint></SequenceData>
SQL> select xdburitype(:targetPath).getClob()
2 from dual
3 /
<SequenceData>
<Header>
<id>285062</id>
<TemplateName>1 dup</TemplateName>
<TemplateVersion>1</TemplateVersion>
<CreUser>AJB2KOR</CreUser>
<CreDate>02-SEP-05</CreDate>
</Header>
<Variables>
<SetPhaseVariables/>
<MeasPhaseVariables>
<MeasPhaseVariable>
<Name>TimeStamp</Name>
<Unit>Sec</Unit>
</MeasPhaseVariable>
</MeasPhaseVariables>
<MonitoredVariables>
<MonitoredVariable>
<Name>Svar b</Name>
<Unit>b</Unit>
</MonitoredVariable>
<MonitoredVariable>
<Name>Svar c</Name>
<Unit>c</Unit>
</MonitoredVariable>
</MonitoredVariables>
</Variables>
<LoadPoint LevelNumber="1" id="114103" Description="LOADPOINT: (werwrwrw)">
<LoopCount InnerLoop="1" OuterLoop="1">
<MonitoredVariables/>
<SetPhase>
<MonitoredVariables/>
<SetPhaseVariables/>
</SetPhase>
<WaitPhase>
<WaitingTime>0</WaitingTime>
<MonitoredVariabl
SQL>The problem is that we will assume the default namespace is the targetNamespace for SB XMLType, which is fine until you try and access a node that is in the 'noNamespace' namespace. Making use of that assumption is bad programming practice, you should always explicitly provide namespace declarations for all namespaces when querying XML.
BTW as you can see you can also get direct access to the contents of a resource using xdburitype.
Similar Messages
-
Hi,
We are using ContentBySearchWebPart to facilitate search through the site.
We have used display template to format the results. We are deploying the web part on the desired page through a feature. We have below markup for web part in the elements.xml file to add the web part -
<webPart xmlns="http://schemas.microsoft.com/WebPart/v3">
<metaData>
<type name="Microsoft.Office.Server.Search.WebControls.ContentBySearchWebPart, Microsoft.Office.Server.Search, Version=15.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" />
<importErrorMessage>Cannot import this Web Part.</importErrorMessage>
</metaData>
<data>
<properties>
<property name="StatesJson" type="string">{}</property>
<property name="UseSharedDataProvider" type="bool">False</property>
<property name="UseSimplifiedQueryBuilder" type="bool">False</property>
<property name="QueryGroupName" type="string">f5646507-4a7a-4d75-b5c4-d435b9128e2a</property>
<property name="LogAnalyticsViewEvent" type="bool">True</property>
<property name="SelectedPropertiesJson" type="string">["Title","Path","Description"]</property>
<property name="PropertyMappings" type="string" />
<property name="ShowAdvancedLink" type="bool">True</property>
<property name="NumberOfItems" type="int">10</property>
<property name="EmitStyleReference" type="bool">True</property>
<property name="ShowPreferencesLink" type="bool">True</property>
<property name="ServerIncludeScriptsJson" type="string">null</property>
<property name="IncludeResultTypeConstraint" type="bool">False</property>
<property name="Height" type="string" />
<property name="MaxPagesBeforeCurrent" type="int">4</property>
<property name="ResultType" type="string" />
<property name="ShowDidYouMean" type="bool">False</property>
<property name="StartingItemIndex" type="int">1</property>
<property name="AlwaysRenderOnServer" type="bool">False</property>
<property name="GroupTemplateId" type="string">~sitecollection/_catalogs/masterpage/Display Templates/Content Web Parts/Group_Content.js</property>
<property name="ResultTypeId" type="string" />
<property name="ItemTemplateId" type="string">~sitecollection/_catalogs/masterpage/Display Templates/Search/Item_LearningGroup.js</property>
<property name="AllowConnect" type="bool">True</property>
<property name="HelpUrl" type="string" />
<property name="ResultsPerPage" type="int">10</property>
<property name="RenderTemplateId" type="string">~sitecollection/_catalogs/masterpage/Display Templates/Content Web Parts/ListWithPaging.js</property>
<property name="AllowEdit" type="bool">True</property>
<property name="AllowZoneChange" type="bool">True</property>
<property name="AddSEOPropertiesFromSearch" type="bool">False</property>
<property name="AdvancedSearchPageAddress" type="string">advanced.aspx</property>
<property name="HitHighlightedPropertiesJson" type="string">["Title","Path","Author","SectionNames","SiteDescription"]</property>
<property name="TitleUrl" type="string" />
<property name="EmptyMessage" type="string" />
<property name="ShowBestBets" type="bool">False</property>
<property name="ShowViewDuplicates" type="bool">False</property>
<property name="AllowHide" type="bool">True</property>
<property name="BypassResultTypes" type="bool">True</property>
<property name="Description" type="string">Content Search Web Part will allow you to show items that are results of a search query you specify. When you add it to the page, this Web Part will show recently modified items from the current site. You can change this setting to show items from another site or list by editing the Web Part and changing its search criteria.As new content is discovered by search, this Web Part will display an updated list of items each time the page is viewed.</property>
<property name="ShowSortOptions" type="bool">False</property>
<property name="ExportMode" type="exportmode">All</property>
<property name="AllowMinimize" type="bool">True</property>
<property name="ShowPersonalFavorites" type="bool">False</property>
<property name="ChromeType" type="chrometype">None</property>
<property name="ShowPaging" type="bool">True</property>
<property name="ChromeState" type="chromestate">Normal</property>
<property name="CatalogIconImageUrl" type="string" />
<property name="HelpMode" type="helpmode">Modeless</property>
<property name="TitleIconImageUrl" type="string" />
<property name="ItemBodyTemplateId" type="string" />
<property name="AlternateErrorMessage" type="string" null="true" />
<property name="Hidden" type="bool">False</property>
<property name="TargetResultTable" type="string">RelevantResults</property>
<property name="AllowClose" type="bool">True</property>
<property name="MissingAssembly" type="string">Cannot import this Web Part.</property>
<property name="ShowResultCount" type="bool">True</property>
<property name="ShowLanguageOptions" type="bool">True</property>
<property name="ShowUpScopeMessage" type="bool">False</property>
<property name="Width" type="string" />
<property name="RepositionLanguageDropDown" type="bool">False</property>
<property name="Title" type="string">Search Learning Groups</property>
<property name="ScrollToTopOnRedraw" type="bool">False</property>
<property name="ShowResults" type="bool">True</property>
<property name="ShowAlertMe" type="bool">False</property>
<property name="OverwriteResultPath" type="bool">True</property>
<property name="PreloadedItemTemplateIdsJson" type="string">null</property>
<property name="MaxPagesAfterCurrent" type="int">1</property>
<property name="ShowDefinitions" type="bool">False</property>
<property name="ShouldHideControlWhenEmpty" type="bool">False</property>
<property name="AvailableSortsJson" type="string">null</property>
<property name="DataProviderJSON" type="string">{"QueryGroupName":"f5646507-4a7a-4d75-b5c4-d435b9128e2a","QueryPropertiesTemplateUrl":"sitesearch://webroot","IgnoreQueryPropertiesTemplateUrl":false,"SourceID":"8413cd39-2156-4e00-b54d-11efd9abdb89","SourceName":"Local SharePoint Results","SourceLevel":"Ssa","CollapseSpecification":"","QueryTemplate":"Path:{SiteCollection.URL} AND :{SearchBoxQuery} ","FallbackSort":[],"FallbackSortJson":"[]","RankRules":[],"RankRulesJson":"[]","AsynchronousResultRetrieval":false,"SendContentBeforeQuery":true,"BatchClientQuery":true,"FallbackLanguage":-1,"FallbackRankingModelID":"","EnableStemming":true,"EnablePhonetic":false,"EnableNicknames":false,"EnableInterleaving":false,"EnableQueryRules":true,"EnableOrderingHitHighlightedProperty":false,"HitHighlightedMultivaluePropertyLimit":-1,"IgnoreContextualScope":true,"ScopeResultsToCurrentSite":false,"TrimDuplicates":false,"Properties":{"TryCache":true,"Scope":"{Site.URL}","UpdateLinksForCatalogItems":true,"EnableStacking":true,"ListId":"60ae8593-eddc-45e0-802a-27f78059ce26","ListItemId":4},"PropertiesJson":"{\"TryCache\":true,\"Scope\":\"{Site.URL}\",\"UpdateLinksForCatalogItems\":true,\"EnableStacking\":true,\"ListId\":\"60ae8593-eddc-45e0-802a-27f78059ce26\",\"ListItemId\":4}","ClientType":"ContentSearchRegular","UpdateAjaxNavigate":true,"SummaryLength":180,"DesiredSnippetLength":90,"PersonalizedQuery":false,"FallbackRefinementFilters":null,"IgnoreStaleServerQuery":false,"RenderTemplateId":"DefaultDataProvider","AlternateErrorMessage":null,"Title":""}</property>
<property name="Direction" type="direction">NotSet</property>
</properties>
</data>
</webPart>
When we are downloading the 'Top Queries by Month' or 'Top Queries by Day' report, while we see numbers in 'Total Queries' and '% of all queries' columns, we are not finding anything in 'Query Text' column, its empty. Not sure while the analytics is
not able to fetch/report the 'Query Text' itself - the report doesnt make any sense without 'Query Text' information.
Is there anything in the web part markup I pasted above- is any of the property value is affecting this?
Or it can be some configuration/error with the logging/analytics process?
Please suggest. Thanks in advance.
Regards,
Mahavir
MOSS programmerHi,
Hope you are doing well. Would you help to try to run the script to start the timer job manually:
Run the script to start the timer job:
==================
$ua = Get-SPTimerJob -Type Microsoft.Office.Server.Search.Analytics.UsageAnalyticsJobDefinition
$ua.GetAnalysisInfo()
$ua = get-sptimerjob -type microsoft.office.server.search.analytics.usageanalyticsjobdefinition
$ua.DisableTimerJobSchedule()
$ua.StartAnalysis()
$ua.EnableTimerJobSchedule()
$ua = Get-SPTimerJob -Identity ("job-usage-log-file-import")
$ua.RunNow()
==================
2. Please install the SharePoint 2013 March update if our version is before this:
SharePoint 2013 March update:
http://support.microsoft.com/kb/2767999
Best Regards,
Dats Luo -
How can I pass/add these results in my Main query's column
Hello Experts
I’m working on a subquery. My subquery works fine and give the results what I need. But how can I pass/add these results in my Main query’s column ‘MGRNAME’. Here is my query
select pc.c_id "Project ID",
cn.c_id "Client ID", cn.c_last "Last Name", cn.c_first "First Name",
pj.mgr_id "Manager ID", pj.project_name "Project", MGRNAME
from project_consultant pc
join consultant cn
on (pc.c_id = cn.c_id)
join project pj
on (pc.p_id = pj.p_id)
where lower(cn.c_last) = 'myers'
and MGRNAME in
( select concat (substr(c_last,1,20),
substr(c_first,1,20))
as MGRNAME from consultant
where c_id in (102, 103)
When I run the above query I got error.
Thanks a lot on advanceI’ve join three tables to get the information about I need. I got everything working expert one part. The subquery
( select concat (substr(c_last,1,20),
substr(c_first,1,20))
as MGRNAME from consultant
where c_id in (102, 103)
Gives me the names of employees I need. The output comes 2 names. I’m trying to add these 2 names in my main query and show the results but I got the following error
Error at Command Line:11 Column:4
Error report:
SQL Error: ORA-00904: "MGRNAME": invalid identifier
00904. 00000 - "%s: invalid identifier"
*Cause:
I can understand there is something wrong with MGRNAME field but not sure what it is. Can somebody point it out?
Once again this is main query with single sub query
select pc.c_id "Project ID",
cn.c_id "Client ID", cn.c_last "Last Name", cn.c_first "First Name",
pj.mgr_id "Manager ID", pj.project_name "Project",
MGRNAME
from project_consultant pc
join consultant cn
on (pc.c_id = cn.c_id)
join project pj
on (pc.p_id = pj.p_id)
where lower(cn.c_last) = 'myers'
and MGRNAME in
( select concat (substr(c_last,1,20),
substr(c_first,1,20))
as MGRNAME from consultant
where c_id in (102, 103)
Hope it helps -
Query a column of data through IFS?
We need to know how to query a column of data through iFS (if this is even possible). For instance, in our database, there is a table ODM_TEST with a column RELEVANT_LOCATION. To get the unique values, we'd just query in SQL:
SELECT DISTINCT(relevant_location) FROM odm_test
WHERE relevant_location is not null
ORDER BY relevant_location
Is there a way of doing that through the iFS API?
nullYou can use Selector or Search API of iFS to do the query. Selector is used for simple queries and Search is used for complex queries.
For example, page 8-9 of Developer Reference of iFS release 9.0.1 has an example of how to use a selector to do the following query -
SELECT * FROM ATTRIBUTE WHERE DATATYPE = BOOLEAN ORDER BY NAME DESC, REQUIRED
You can also fine examples of how to use Search classes in the same chapter.
I hope it helps.
null -
Query of Query count(column) returns blank not zero
This appears to be a bug in 7,0,1,116466 and 8,0,1,195765
Query of Query count(column) or count(*) returns blank not
zero when there are no matches. Properly returns a number when
there are query matches.
e.g. select count(i_id) from PersonnelQuery where i_id <
100
Where does one report these?scottcook,
This was a known bug in ColdFusion 6.x which has apparently
not been fixed.
Bug in CF6 (See the Comments section of the page linked
below)
http://livedocs.adobe.com/coldfusion/6.1/htmldocs/using_29.htm
Workaround
http://www.bennadel.com/blog/244-ColdFusion-Query-Of-Queries-Odd-COUNT-Behavior.htm
To report this as a bug
http://www.adobe.com/cfusion/mmform/index.cfm?name=wishform -
I have a problem like this
There is a table which has two columns. (actually we can ignore other columns) say X and Y. entry in Y says that X uses Y. This is soemthing like a hierachy in a mesh structure.
If i do a select on Y i can get the places where Y is used only in one level of the heirachy. (just above level of Y) But I want to get the places where Y is used in all the places not just as direct decendant.
For example say there are 3 entries A,B,C. A use children a1,a2 and a2 use a3. B use b1,a2,b2. C use c1,c2 and c2 use B.
So what i want is when i make a query where entry = 'a3' my expected result should be a2,A,B,c2 and C. Can anyone help me to do this..
Hope this is clearDuplicate Thread.
Answers over here...
Query on column hierachy -
Forms 6.0 how to query clob column with oracle 9.2 DB
hi every body,
i made install for oracle 9.2 oracle DB every thing goes ok but when i made query in my form version 6.0 which have CLOB column the form closed automatically without any message?
and just for know when i run the same form with oracle 8.1.7 DB the form made query normally without any problem.
i want your help please.
Message was edited by:
mshaqalaihI know there was a problem in 6i where you would get a crash if your query returned more than {Max Length} characters of the field representing the CLOB column.
-
SAP Query SQ01 column limitation issue
Hi
At SQ01, I have created a number of custom reports via SAP Query.
Its a great tool and all, but I am running into a problem where there is a 255 character limitation when I create a Statistics view (where it summarizes values by characters I choose).
In the SQ01 Query screen, this is controlled by the columns field under the heading list format and if I list too many objects, I get a message stating report has exceeded 255 character limitation.
Is there any way I can modify this value, so I can exceed it (say 500?)?
For us, we use many query reports in our daily reporting so it would be worth modifying.
If anyone has any info on this, please advise (or feel free to PM me!)
Regards
KenNaimesh,
Thanks for your reply.
How can I accomplish this? And will it still show the data one the same screen?
Regards
Ken -
SSMS 2012: Using CTE in a query - Invalid column name 'EmployeeID' !!??
Hi all,
From Page 88 of the Book "SQL Programming & Database Design Using Microsoft SQL Server 2012" written by Kalman Toth, I copied the following code of Using CTE in a query:
-- CTETest2.sql /// saved in C:\My Documents\SQL Server Management Studio\
----Page 88 of Book by Toth === Using CTE in a query ----- 13 March 2015
--Using CTE in a query
;WITH CTE (SalesPersonID, NumberOfOrders, MostRecentOrderDate)
AS (SELECT SalesPersonID, COUNT(*), CONVERT(date, MAX(OrderDate))
FROM Sales.SalesOrderHeader GROUP BY SalesPersonID )
--Start of outer (main) query
SELECT E.EmployeeID,
OE.NumberOfOrders AS EmpOrders,
OE.MostRecentOrderDate AS EmpLastOrder,
E.ManagerID,
OM.NumberOfOrders AS MgrOrders,
OM.MostRecentOrderDate AS MgrLastOrder
FROM HumanResources.Employee AS E
INNER JOIN CTE AS OE ON E.EmployeeID = OE.SalesPersonID
LEFT OUTER JOIN CTE AS OM ON E.ManagerID = OM.SalesPersonID
In my SQL Server 2012 Management Studio, I executed this set of code and I got the following fatal error:
Msg 207, Level 16, State 1, Line 16
Invalid column name 'EmployeeID'.
I have no clues why I got this error message in this .sql trial of my second practice in doing CTE. Please kindly help and let me know where I made mistake and how to resolve this problem.
Thanks in advance,
Scott ChangHi scott_morris-ga, Thanks for your nice response.
I changed EmployeeID to BusinessEntityID as you pointed out and executed the revised code:
-- CTETest2.sql /// saved in C:\My Documents\SQL Server Management Studio\
----Page 88 of Book by Toth === Using CTE in a query ----- 13 March 2015
--Using CTE in a query
;WITH CTE (SalesPersonID, NumberOfOrders, MostRecentOrderDate)
AS (SELECT SalesPersonID, COUNT(*), CONVERT(date, MAX(OrderDate))
FROM Sales.SalesOrderHeader GROUP BY SalesPersonID )
--Start of outer (main) query
SELECT E.BusinessEntityID,
OE.NumberOfOrders AS EmpOrders,
OE.MostRecentOrderDate AS EmpLastOrder,
E.ManagerID,
OM.NumberOfOrders AS MgrOrders,
OM.MostRecentOrderDate AS MgrLastOrder
FROM HumanResources.Employee AS E
INNER JOIN CTE AS OE ON E.BusinessEntityID = OE.SalesPersonID
LEFT OUTER JOIN CTE AS OM ON E.ManagerID = OM.SalesPersonID
I got 2 new error messages:
Msg 207, Level 16, State 1, Line 17
Invalid column name 'ManagerID'.
Msg 207, Level 16, State 1, Line 12
Invalid column name 'ManagerID'.
I have no ideas what should be used to replace 'ManagerID' in my revised code. Could you please help again and give me the right thing to replace the 'ManagerID'? By the way, where in the AdventureWorks do you find the right things? Please enlighten
me in this matter.
Many Thanks again, Scott Chang -
Query on column with comma separated values
I have a proposed table with unnormalized data like the following:
ID COLA COLB REFLIST
21 xxx zzz 24,25,78,412
22 xxx xxx 21
24 yyy xxx 912,22
25 zzz fff 433,555,22
.. ... ... ...There are 200 million rows. There is maximum of about 10 IDs in the REFLIST, though typically two or three. How could I efficiently query this data on the REFLIST column? e.g. something like:
SELECT id FROM mytable WHERE :myval in reflistLogically there is a many to many relationship between rows in this table. The REFLIST column contains pointers to ID values elsewhere in the table. The data could be normalized so that the relationship keys are in a separate table (in fact this is the current solution that we want to change).
ID REF
21 24
21 25
21 78
21 412
22 21
24 912
... ...The comma separated list seems instinctively like a bad idea, however there are various reasons for proposing it. The main reason is because the source for this data has it structured like the REFLIST example. It is an OLTP-like system rather than a data warehouse. The source code (and edit performance) would benefit greatly from not having to maintain the relationship table as the data changes.
Going back to querying the REFLIST column, the problem seems to be building an approriate index for the data. The ideas proposed so far are:
<li>Make a materialized view that presents the relationships as normalized (e.g. as in the example with ID, REF columns above), then index the plain column - the various methods of writing the view SQL have been widely posted.
<li>Use a Oracle Text Index (not something I have ever had call to use before).
Any other ideas? Its Oracle 10.2, though 11g could be possible.
Thanks
JimSomething like this ?
This is test demo on my 11.2.0.1 Windows XP
SQL> create table test (id number,reflist varchar2(30));
Table created.
SQL> insert into test values (21,'24,25,78,412');
1 row created.
SQL> insert into test values (22,'21');
1 row created.
SQL> insert into test values (24,'912,22');
1 row created.
SQL> insert into test values (25,'433,555,22');
1 row created.
SQL> select * from test
2 where
3 ',' || reflist || ',' like '%,22,%';
ID REFLIST
24 912,22
25 433,555,22
SQL>Source:http://stackoverflow.com/questions/7212282/is-it-possible-to-query-a-comma-separated-column-for-a-specific-value
Regards
Girish Sharma
Edited by: Girish Sharma on Jul 12, 2012 2:31 PM -
Querying CHAR columns with character length semantics unreliable
Hi again,
It appears that there is a bug in the JDBC drivers whereby it is highly unlikely that the values of CHAR columns that use character length semantics can be accurately queried using ResultSet.getString(). Instead, the drivers return the value padded with space (0x#20) characters out to a number of bytes equal to the number of characters multiplied by 4. The number of bytes varies depending on the number and size of any non-ascii characters stored in the column.
For instance, if I have a CHAR(1) column, a value of 'a' will return 'a ' (4 characters/bytes are returned), a value of '\u00E0' will return '\u00E0 ' (3 characters / 4 bytes), and a value of '\uE000' will return '\uE000 ' (2 characters / 4 bytes).
I'm currently using version 9.2.0.3 of the standalone drivers (ojdbc.jar) with JDK 1.4.1_04 on Redhat Linux 9, connecting to Oracle 9.2.0.2.0 running on Solaris.
The following sample code can be used to demonstrate the problem (where the DDL at the top of the file must be executed first):
import java.sql.*;
import java.util.*;
This sample generates another bug in the Oracle JDBC drivers where it is not
possible to query the values of CHAR columns that use character length semantics
and are NOT full of non-ascii characters. The inclusion of the VARCHAR2 column
is just a control.
CREATE TABLE TMP2
TMP_ID NUMBER(10) NOT NULL PRIMARY KEY,
TMP_CHAR CHAR(10 CHAR),
TMP_VCHAR VARCHAR2(10 CHAR)
public class ClsCharSelection
private static String createString(char character, int length)
char characters[] = new char[length];
Arrays.fill(characters, character);
return new String(characters);
} // private static String createString(char, int)
private static void insertRow(PreparedStatement ps,
int key, char character)
throws SQLException
ps.setInt(1, key);
ps.setString(2, createString(character, 10));
ps.setString(3, createString(character, 10));
ps.executeUpdate();
} // private static String insertRow(PreparedStatement, int, char)
private static void analyseResults(PreparedStatement ps, int key)
throws SQLException
ps.setInt(1, key);
ResultSet results = ps.executeQuery();
results.next();
String tmpChar = results.getString(1);
String tmpVChar = results.getString(2);
System.out.println(key + ", " + tmpChar.length() + ", '" + tmpChar + "'");
System.out.println(key + ", " + tmpVChar.length() + ", '" + tmpVChar + "'");
results.close();
} // private static void analyseResults(PreparedStatement, int)
public static void main(String argv[])
throws Exception
Driver driver = (Driver)Class.forName(
"oracle.jdbc.driver.OracleDriver").newInstance();
DriverManager.registerDriver(driver);
Connection connection = DriverManager.getConnection(
argv[0], argv[1], argv[2]);
PreparedStatement ps = null;
try
ps = connection.prepareStatement(
"DELETE FROM tmp2");
ps.executeUpdate();
ps.close();
ps = connection.prepareStatement(
"INSERT INTO tmp2 ( tmp_id, tmp_char, tmp_vchar " +
") VALUES ( ?, ?, ? )");
insertRow(ps, 1, 'a');
insertRow(ps, 2, '\u00E0');
insertRow(ps, 3, '\uE000');
ps.close();
ps = connection.prepareStatement(
"SELECT tmp_char, tmp_vchar FROM tmp2 WHERE tmp_id = ?");
analyseResults(ps, 1);
analyseResults(ps, 2);
analyseResults(ps, 3);
ps.close();
connection.commit();
catch (SQLException e)
e.printStackTrace();
connection.close();
} // public static void main(String[])
} // public class ClsColumnInsertionFYI, this has been mentioned as early as November last year:
String with length 1 became 4 when nls_lang_semantics=CHAR
and was also brought up in Feburary:
JDBC thin driver pads CHAR col to byte size when NLS_LENGTH_SEMANTICS=CHAR -
The rows of a query become columns
Hi , everybody
I have an aggregated query . The format of the result is :
COL1 COL2 COL3
==== ==== ====
VAL1 1800 CVAL1
VAL1 780 CVAL2
VAL1 800 CVAL3
VAL2 3450 CVAL2
VAL2 890 CVAL3
e.t.c.
I want ,the quicker way, the format of the result to be as follows (regarding the above sample data):
COL1 CVAL1 CVAL2 CVAL3
==== ==== ===== ======
VAL1 1800 780 800
VAL2 3450 890
In other words , I want the each value in COL1 appear just one time and the data in other columns to be developed ...as columns
Thanks , SimonHi,
This will help.
ABANSVI@CTSQA>SELECT * FROM TEST;
COL1 COL2 COL3
VAL1 1800 CVAL1
VAL1 780 CVAL2
VAL1 800 CVAL3
VAL2 3450 CVAL2
VAL2 890 CVAL3
Elapsed: 00:00:00.47
ABANSVI@CTSQA>SELECT COL1,
2 MAX(DECODE(COL3, 'CVAL1', SM, NULL)) CVAL1,
3 MAX(DECODE(COL3, 'CVAL2', SM, NULL)) CVAL2,
4 MAX(DECODE(COL3, 'CVAL3', SM, NULL)) CVAL3
5 FROM (
6 SELECT COL1, COL3, SUM(COL2) SM FROM TEST
7 GROUP BY COL1, COL3)
8 GROUP BY COL1;
COL1 CVAL1 CVAL2 CVAL3
VAL1 1800 780 800
VAL2 3450 890
Elapsed: 00:00:00.34Vineet -
[Swing] JTable & Oracle DB: SQL Query for Column Names Change
Hello,
I apologise for the 'stupid' thread subject name.
Now i have a JTable wich i fill with rows from an Oracle DB.
The query is something like this: "SELECT location_id, location_name FROM locations*bold*", and in the table i will have the columns names LOCATION_ID & LOCATION_NAME.
I want to change this query like: "SELECT location_id "Location ID", location_name "Location Name" FROM locations".
The only problem is that i CAN NOT insert "" inside ""
So if anyone know how to fix this 'problem' please share that with me.
Thank you,
B.found it.. \" \"
:) -
Tabular form query using column values delimiter
I wanted to know, if i can query a tabular block by entering the column values (primary key) as semicolon delimited and update required fields. Please let me know.
Requirement:-
User will enter 5 values as "AB1; AB2; AB3; AB4; AB5"
After entering I need to write a plsql code to query the tabular form as follows
PrimaryCol SecCol
AB1 IN
AB2 IN
AB3 OUT
AB4 IN
AB5 ON
Then I will update the columns accordingly.
Please help me.You could put something like this in the WHERE-clause (assuming that :BLOCK.QUERYDATA contains your value AB1;AB2;AB3;AB4; )
INSTR (';' || PK_COLUMN || ';', ';' || :BLOCK.QUERYDATA || ';')>0Maybe you have to additionally eliminate space in :BLOCK.QUERYDATA -
I'm working with an embedded db query that specifies columns
by name in the result set, i.e., no *. However, the order of the
columns in the result set seem to be quite random - or at least
dependent on which column is being searched. I'm showing the
results via "resultsGrid." How do I enforce a consistent column
order in query results?
Thanks,
AlWhat you describe boils down to a reinvention of materialized views.
Did you consider using them?
Sybrand Bakker
Senior Oracle DBA
Maybe you are looking for
-
Where can I purchase a tri-wing screwdriver kit?
Hey everyone. I'm trying to purchase a y1 Tri-wing screwdriver locally (NYC Stores). Any suggestions? Thanks.
-
What resolution with log & transfer
When a 1920 x 1080i AVCHD clip is brought into FCE HD via log and transfer, it is my understanding that it goes from AVCHD to AIC. What would the resolution be after the import? In iMovie the clips become 1920 x 540 AIC, I am hoping for something mor
-
Count the Pass/ Fail in a DAQ reading testing ?
I want to write the while loop to read the DAQ signal. Each time, the DAQ input signal is compared with the spec. limit. The signal that is within the limit will be recorded as " Pass " while the signal out of spec. will be recorded as " Fail ". At t
-
Print spool depending on criteria
Hi ABAPers, I have the requirement to print spool jobs generated by transaction VF06 to PDF OR to a printer device. For some company codes the customer want the printing to be on PDF files, stored on there server. For other company codes it can print
-
OSX 10.9 update removed java - how to fix that?
After updating to OS 10.9 I could no longer us my most important app PHPStorm because it relies on java and the OSX 10.9 installer sabotaged it. When I type java on the console it now says No Java runtime present, requesting install. request, hu? ***