SQL query result shoes value ids instead of value names
Hi All,
Pleaes i need help.
When selecting top 1000 result from a table, it give me a lot of result taht are useful for me. But one column named "subcategory", it give me the Subcategory ID instead of Subcategory NAme
The Subcategory Information are taken from another column that belong to another table (sometimes from another DB)
I would like to substitue (or somethink similar) the subcategory ID's with Subcagtegory names.
here details:
Date
Category Name (CATEGORY)
Subcategory ID (ITEM ID)
Date
Name of Table 1 belonging to Another DB 1 in Altro DB
Item ID, that is present in a Column of Table 1
Date
Name of Table 4 belonging to Another DB 1 in Altro DB
Item ID, that is present in a Column of Table 4
Date
Name of Table 1 Belonging to Another DB 1 in Altro DB
Item ID, that is present in a Column of Table 1
Date
Name of Table 2 Belonging to Another DB 1 in Altro DB
Item ID, that is present in a Column of Table 2
Can you help me please?
thanks
I think what you need is a simple join
ie like below
SELECT t.[Date],t.CATEGORY,s.SUBCATEGORYNAME,.. other columns
FROM YourTable t
INNER JOIN AltroDB.dbo.SUbCategoryTable s
ON s.IDField = t.ITEMID
IDField is field corresponding to ITEMID value in subcategory table.
Please Mark This As Answer if it helps to solve the issue Visakh ---------------------------- http://visakhm.blogspot.com/ https://www.facebook.com/VmBlogs
Similar Messages
-
SQL Query results to CSV as two worksheets
I'm trying to take two SQL queries and get the results sent to a CSV file on two worksheets. Looking online I have not found a solid example of using the Excel ComObject to create a CSV then add a new worksheet to the CSV file. An added bonus
would be using AutoFit on the columns so everything is easily visible.
Code found online got me the following script which does work, however it takes 12 minutes to pipe the SQL queries to Excel. Switching to a CSV and the script executes in 5 seconds.
This is another nice to have, I was also looking the best way to look at the results (only 1 column) and depending on the length of the data, insert what Excel would call a Cell thereby shifting cells RIGHT but so far have found no clear examples of how
to accomplish that. My guess would be modifying my SQL queries but I've posted a question on StackOverFlow and someone suggested modifying the PowerShell Table created from the SQL dataset.Tables
Code:
$docs = "C:\Scripts\Output.xlsx"
If (Test-Path $docs){Remove-Item $docs}
Function Run-Query {
param([string[]]$queries,[string[]]$sheetnames)
## - Create an Excel Application instance:
$xlsObj = New-Object -ComObject Excel.Application
$xlsObj.DisplayAlerts = $false
$xlsWb = $xlsobj.Workbooks.Add(1)
## - Create new Workbook and Sheet (Visible = 1 / 0 not visible)
$xlsObj.Visible = 0
$time = 2
for ($i = 0; $i -lt $queries.Count; $i++){
$percentage = $i / $time
$remaining = New-TimeSpan -Seconds ($time - $i)
$message = "{0:p0} complete" -f $percentage, $remaining
Write-Progress -Activity "Creating Daily Reboot Spreadsheet" -status $message -PercentComplete ($percentage * 100)
$query = $queries[$i]
$sheetname = $sheetnames[$i]
$xlsSh = $xlsWb.Worksheets.Add([System.Reflection.Missing]::Value, $xlsWb.Worksheets.Item($xlsWb.Worksheets.Count))
$xlsSh.Name = $sheetname
### SQL query results sent to Excel
$SQLServer = 'ServerName'
$Database = 'DataBase'
## - Connect to SQL Server using non-SMO class 'System.Data':
$SqlConnection = New-Object System.Data.SqlClient.SqlConnection
$SqlConnection.ConnectionString = "Server = $SQLServer; Database = $Database; Integrated Security = True"
$SqlCmd = New-Object System.Data.SqlClient.SqlCommand
$SqlCmd.CommandText = $query
$SqlCmd.Connection = $SqlConnection
## - Extract and build the SQL data object '$Table2':
$SqlAdapter = New-Object System.Data.SqlClient.SqlDataAdapter
$SqlAdapter.SelectCommand = $SqlCmd
$DataSet = New-Object System.Data.DataSet
$SqlAdapter.Fill($DataSet)
$SqlConnection.Close()
$Table1 = $DataSet.Tables["Table"]
## - Build the Excel column heading:
[Array] $getColumnNames = $Table1.Columns | SELECT ColumnName
## - Build column header:
[Int] $RowHeader = 1
foreach ($ColH in $getColumnNames)
$xlsSh.Cells.item(1, $RowHeader).font.bold = $true
$xlsSh.Cells.item(1, $RowHeader) = $ColH.ColumnName
$RowHeader++
## - Adding the data start in row 2 column 1:
[Int] $rowData = 2
[Int] $colData = 1
foreach ($rec in $Table1.Rows)
foreach ($Coln in $getColumnNames)
## - Next line convert cell to be text only:
$xlsSh.Cells.NumberFormat = "@"
## - Populating columns:
$xlsSh.Cells.Item($rowData, $colData) = $rec.$($Coln.ColumnName).ToString()
$ColData++
$rowData++; $ColData = 1
## - Adjusting columns in the Excel sheet:
$xlsRng = $xlsSH.usedRange
[void] $xlsRng.EntireColumn.AutoFit()
}#End For loop.
#Delete unwanted Sheet1.
$xlsWb.Sheets.Item('Sheet1').Delete()
#Set Monday to Active Sheet upon opening Workbook.
$xlsWb.Sheets.Item('Cert').Activate()
## ---------- Saving file and Terminating Excel Application ---------- ##
$xlsFile = "C:\Scripts\Output.xlsx"
[void] $xlsObj.ActiveWorkbook.SaveAs($xlsFile)
$xlsObj.Quit()
## - End of Script - ##
start-sleep 2
While ([System.Runtime.Interopservices.Marshal]::ReleaseComObject($xlsRng)) {'cleanup xlsRng'}
While ([System.Runtime.Interopservices.Marshal]::ReleaseComObject($xlsSh)) {'cleanup xlsSh'}
While ([System.Runtime.Interopservices.Marshal]::ReleaseComObject($xlsWb)) {'cleanup xlsWb'}
While ([System.Runtime.Interopservices.Marshal]::ReleaseComObject($xlsObj)) {'cleanup xlsObj'}
[gc]::collect() | Out-Null
[gc]::WaitForPendingFinalizers() | Out-Null
}#End Function
$queries = @()
$queries += "Query1"
$queries += "Query2"
$sheetnames = @('Cert','Prod')
Run-Query -queries $queries -sheetnames $sheetnamesHere's what I ended up with that accomplishes my goal. I learned it's not possible to create a CSV with two worksheets since Excel will allow this but the CSV cannot be saved with the second worksheet. Instead, I create two CSV files then merge
them into one Excel workbook, one CSV per worksheet. In my case, this happens in 5 seconds. There is one thing which must be mentioned, I've seen this script fail the first time it is run but will successfully run the second time.
Also note, after much trial and error, this code correctly cleans up the Excel ComObject!! -Thanks go to JRV.
$docs = "D:\Scripts\MonthlyReboots.xlsx"
IF (Test-Path $docs){Remove-Item $docs}
$csv1 = "D:\Scripts\Cert.csv"
IF (Test-Path $csv1){Remove-Item $csv1}
$csv2 = "D:\Scripts\Prod.csv"
IF (Test-Path $csv2){Remove-Item $csv2}
Function Run-Query {
param([string[]]$queries,[string[]]$sheetnames,[string[]]$filenames)
Begin{
$SQLServer = 'ServerName'
$Database = 'DataBase'
$SqlConnection = New-Object System.Data.SqlClient.SqlConnection
$SqlConnection.ConnectionString = "Server = $SQLServer; Database = $Database; Integrated Security = True"
$Excel = New-Object -ComObject Excel.Application
$Excel.Visible = 0
$dest = $Excel.Workbooks.Add(1)
}#End Begin
Process{
For($i = 0; $i -lt $queries.Count; $i++){
$SqlCmd = New-Object System.Data.SqlClient.SqlCommand
$SqlCmd.CommandText = $queries[$i]
$SqlCmd.Connection = $SqlConnection
$SqlAdapter = New-Object System.Data.SqlClient.SqlDataAdapter
$SqlAdapter.SelectCommand = $SqlCmd
$DataSet = New-Object System.Data.DataSet
$SqlAdapter.Fill($DataSet)
$DataSet.Tables[0] | Export-Csv -NoTypeInformation -Path "D:\Scripts\$($sheetnames[$i]).csv" -Force
}#end for loop.
}#End Process
End{
$SqlConnection.Close()
#Excel magic test!
For($i = 0; $i -lt $queries.Count; $i++){
$loopy = (Resolve-Path -Path $filenames[$i]).ProviderPath
$Book = $Excel.Workbooks.Open($loopy)
$next = $Excel.workbooks.Open($loopy)
$next.ActiveSheet.Move($dest.ActiveSheet)
$xlsRng = $dest.ActiveSheet.UsedRange
$xlsRng.EntireColumn.AutoFit() | Out-Null
$dest.sheets.item('Sheet1').Delete()
$xlsFile = "D:\Scripts\MonthlyReboots.xlsx"
[void] $Excel.ActiveWorkbook.SaveAs($xlsFile)
$Excel.Quit()
While ([System.Runtime.Interopservices.Marshal]::ReleaseComObject($xlsRng)) {'cleanup xlsRng'}
While ([System.Runtime.Interopservices.Marshal]::ReleaseComObject($next)) {'cleanup xlsSh'}
While ([System.Runtime.Interopservices.Marshal]::ReleaseComObject($Book)) {'cleanup xlsWb'}
While ([System.Runtime.Interopservices.Marshal]::ReleaseComObject($Excel)) {'cleanup xlsObj'}
[gc]::collect() | Out-Null
[gc]::WaitForPendingFinalizers() | Out-Null
}#End end block.
}#End function run-query.
$queries = @()
$queries += @'
Select * from table1
$queries += @'
Select * from table2
$sheetnames = @("Cert","Prod")
$filenames = @("D:\Scripts\Prod.csv","D:\Scripts\Cert.csv")
Run-Query -queries $queries -sheetnames $sheetnames -filenames $filenames
Start-Sleep -Milliseconds 50
Invoke-Item D:\Scripts\MonthlyReboots.xlsx -
Set Text Item To SQL Query Result
I am trying to set a text item to a SQL query result. Something like the following:
(I am trying to accomplish this in the SOURCE portion, set to 'SQL Query' source type, of the text item properties)
SELECT empno FROM emp WHERE empno = :SEARCH_EMPNO;
This only displays as the literal text when the application renders and not the value from the SQL query.
I apologize if this has already been posted but I could not find what I am looking for. I have seen posts that reference a pre-region computation but do not know the exact steps to accomplish the results I want.
Thanks in advance for anyone's time to help me with my issue.
KyleScott,
The literal that displayed (I have fixed it) was the actual SQL statement: SELECT empno FROM emp WHERE empno = :SEARCH_EMPNO;
I have resolved the issue, using SQL Query as the "Source Type" and Always, replacing any existing value in session state as the "Source Used" for the properties of the item.
What I was trying to accomplish is a search text item that would return the data for that record in a table into other text items, for each column in that record, for update; based on the search text item as a unique SQL query search for that record.
Thank you for your quick reply!
Kyle -
How could I replace hard coded value in my sql query with constant value?
Hi all,
Could anyone help me how to replace hardcoded value in my sql query with constant value that might be pre defined .
PROCEDURE class_by_day_get_bin_data
in_report_parameter_id IN NUMBER,
in_site_id IN NUMBER,
in_start_date_time IN TIMESTAMP,
in_end_date_time IN TIMESTAMP,
in_report_level_min IN NUMBER,
in_report_level_max IN NUMBER
IS
bin_period_length NUMBER(6,0);
BEGIN
SELECT MAX(period_length)
INTO bin_period_length
FROM bin_data
JOIN site_to_data_source_lane_v
ON bin_data.data_source_id = site_to_data_source_lane_v.data_source_id
JOIN bin_types
ON bin_types.bin_type = bin_data.bin_type
WHERE site_to_data_source_lane_v.site_id = in_site_id
AND bin_data.start_date_time >= in_start_date_time - numtodsinterval(1, 'DAY')
AND bin_data.start_date_time < in_end_date_time + numtodsinterval(1, 'DAY')
AND bin_data.bin_type = 2
AND bin_data.period_length <= 60;
--Clear the edr_class_by_day_bin_data temporary table and populate it with the data for the requested
--report.
DELETE FROM edr_class_by_day_bin_data;
SELECT site_to_data_source_lane_v.site_id,
site_to_data_source_lane_v.site_lane_id,
site_to_data_source_lane_v.site_direction_id,
site_to_data_source_lane_v.site_direction_name,
bin_data_set.start_date_time,
bin_data_set.end_date_time,
bin_data_value.bin_id,
bin_data_value.bin_value
FROM bin_data
JOIN bin_data_set
ON bin_data.bin_serial = bin_data_set.bin_serial
JOIN bin_data_value
ON bin_data_set.bin_data_set_serial = bin_data_value.bin_data_set_serial
JOIN site_to_data_source_lane_v
ON bin_data.data_source_id = site_to_data_source_lane_v.data_source_id
AND bin_data_set.lane = site_to_data_source_lane_v.data_source_lane_id
JOIN (
SELECT CAST(report_parameter_value AS NUMBER) lane_id
FROM report_parameters
WHERE report_parameters.report_parameter_id = in_report_parameter_id
AND report_parameters.report_parameter_group = 'LANE'
AND report_parameters.report_parameter_name = 'LANE'
) report_lanes
ON site_to_data_source_lane_v.site_lane_id = report_lanes.lane_id
JOIN (
SELECT CAST(report_parameter_value AS NUMBER) class_id
FROM report_parameters
WHERE report_parameters.report_parameter_id = in_report_parameter_id
AND report_parameters.report_parameter_group = 'CLASS'
AND report_parameters.report_parameter_name = 'CLASS'
) report_classes
ON bin_data_value.bin_id = report_classes.class_id
JOIN edr_rpt_tmp_inclusion_table
ON TRUNC(bin_data_set.start_date_time) = TRUNC(edr_rpt_tmp_inclusion_table.date_time)
WHERE site_to_data_source_lane_v.site_id = in_site_id
AND bin_data.start_date_time >= in_start_date_time - numtodsinterval(1, 'DAY')
AND bin_data.start_date_time < in_end_date_time + numtodsinterval(1, 'DAY')
AND bin_data_set.start_date_time >= in_start_date_time
AND bin_data_set.start_date_time < in_end_date_time
AND bin_data.bin_type = 2
AND bin_data.period_length = bin_period_length;
END class_by_day_get_bin_data;In the above code I'm using the hard coded value 2 for bin type
bin_data.bin_type = 2But I dont want any hard coded number or string in the query.
How could I replace it?
I defined conatant value like below inside my package body where the actual procedure comes.But I'm not sure whether I have to declare it inside package body or inside the procedure.
bin_type CONSTANT NUMBER := 2;But it does't look for this value. So I'm not able to get desired value for the report .
Thanks.
Edited by: user10641405 on May 29, 2009 1:38 PMDeclare the constant inside the procedure.
PROCEDURE class_by_day_get_bin_data(in_report_parameter_id IN NUMBER,
in_site_id IN NUMBER,
in_start_date_time IN TIMESTAMP,
in_end_date_time IN TIMESTAMP,
in_report_level_min IN NUMBER,
in_report_level_max IN NUMBER) IS
bin_period_length NUMBER(6, 0);
v_bin_type CONSTANT NUMBER := 2;
BEGIN
SELECT MAX(period_length)
INTO bin_period_length
FROM bin_data
JOIN site_to_data_source_lane_v ON bin_data.data_source_id =
site_to_data_source_lane_v.data_source_id
JOIN bin_types ON bin_types.bin_type = bin_data.bin_type
WHERE site_to_data_source_lane_v.site_id = in_site_id
AND bin_data.start_date_time >=
in_start_date_time - numtodsinterval(1, 'DAY')
AND bin_data.start_date_time <
in_end_date_time + numtodsinterval(1, 'DAY')
AND bin_data.bin_type = v_bin_type
AND bin_data.period_length <= 60;
--Clear the edr_class_by_day_bin_data temporary table and populate it with the data for the requested
--report.
DELETE FROM edr_class_by_day_bin_data;
INSERT INTO edr_class_by_day_bin_data
(site_id,
site_lane_id,
site_direction_id,
site_direction_name,
bin_start_date_time,
bin_end_date_time,
bin_id,
bin_value)
SELECT site_to_data_source_lane_v.site_id,
site_to_data_source_lane_v.site_lane_id,
site_to_data_source_lane_v.site_direction_id,
site_to_data_source_lane_v.site_direction_name,
bin_data_set.start_date_time,
bin_data_set.end_date_time,
bin_data_value.bin_id,
bin_data_value.bin_value
FROM bin_data
JOIN bin_data_set ON bin_data.bin_serial = bin_data_set.bin_serial
JOIN bin_data_value ON bin_data_set.bin_data_set_serial =
bin_data_value.bin_data_set_serial
JOIN site_to_data_source_lane_v ON bin_data.data_source_id =
site_to_data_source_lane_v.data_source_id
AND bin_data_set.lane =
site_to_data_source_lane_v.data_source_lane_id
JOIN (SELECT CAST(report_parameter_value AS NUMBER) lane_id
FROM report_parameters
WHERE report_parameters.report_parameter_id =
in_report_parameter_id
AND report_parameters.report_parameter_group = 'LANE'
AND report_parameters.report_parameter_name = 'LANE') report_lanes ON site_to_data_source_lane_v.site_lane_id =
report_lanes.lane_id
JOIN (SELECT CAST(report_parameter_value AS NUMBER) class_id
FROM report_parameters
WHERE report_parameters.report_parameter_id =
in_report_parameter_id
AND report_parameters.report_parameter_group = 'CLASS'
AND report_parameters.report_parameter_name = 'CLASS') report_classes ON bin_data_value.bin_id =
report_classes.class_id
JOIN edr_rpt_tmp_inclusion_table ON TRUNC(bin_data_set.start_date_time) =
TRUNC(edr_rpt_tmp_inclusion_table.date_time)
WHERE site_to_data_source_lane_v.site_id = in_site_id
AND bin_data.start_date_time >=
in_start_date_time - numtodsinterval(1, 'DAY')
AND bin_data.start_date_time <
in_end_date_time + numtodsinterval(1, 'DAY')
AND bin_data_set.start_date_time >= in_start_date_time
AND bin_data_set.start_date_time < in_end_date_time
AND bin_data.bin_type = v_bin_type
AND bin_data.period_length = bin_period_length;
END class_by_day_get_bin_data; -
Displaying SQL Query results in rows instead of Columns
Hi,
I'm fairly new to Oracle so forgive me if this is a really stupid question.
I used Mysql for a while and if I wanted to display query results in rows instead of columns I could end the SQL command with '\G' instead of a semicolon.
This would give me output like...
Column_1: AAAA
Column_2: BBBB
Column_3: CCCC
Instead of the normal
Column_1 Column_2 Column_3
AAAAAA BBBBBBB CCCCCCC
Is there an equivalent in SQLPlus to the MySQL \G termination?
Thanks.
John> so forgive me if this is a really stupid question.
It is certainly not a stupid question, but pivoting is a very frequently asked and answered question:
[url http://forums.oracle.com/forums/search.jspa?threadID=&q=pivot&objID=f75&dateRange=all&userID=&numResults=15]http://forums.oracle.com/forums/search.jspa?threadID=&q=pivot&objID=f75&dateRange=all&userID=&numResults=15
In 11g you have special PIVOT and UNPIVOT functions.
Regards,
Rob. -
Pass jstl sql query result to jsp
Hi I have the following code which works perfectly
<%@ taglib prefix="sql" uri="http://java.sun.com/jsp/jstl/sql" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<sql:setDataSource dataSource="jdbc/dbtest"/>
<sql:query var="items" sql="SELECT * FROM homepagesubscriptions">
</sql:query>
<table border="0" align="center" valign="top">
<c:forEach var="row" items="${items.rows}" begin = "0" end="10" >
<tr>
<td>
<img src="${row.imgurl}" width="100" height = "100"></a>
</td>
<tr>
</c:forEach>
</table> Now what I want is to perform the query in one page and then display the data in another, as such
index.jsp
<%@ taglib prefix="sql" uri="http://java.sun.com/jsp/jstl/sql" %>
<sql:setDataSource dataSource="jdbc/dbtest"/>
<sql:query var="items" sql="SELECT * FROM homepagesubscriptions">
</sql:query>
<!-- NOT SURE WHAT TO DO HERE
<jsp:useBean id="resultBean" scope="request"
class="javax.servlet.jsp.jstl.sql.ResultSupport" />
<jsp:setProperty name="rs" property="rs" />
<jsp:forward page="test.jsp" />
-->
test.jsp
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<c:set var="items" value="${resultBean}" />
<table border="0" align="center" valign="top">
<c:forEach var="row" items="${items.rows}" begin = "0" end="10" >
<tr>
<td>
<img src="${row.imgurl}" width="100" height = "100"></a>
</td>
<tr>
</c:forEach>
</table> I know in index.jsp I can use jsp forward and usebean but am not sure how to? What type is the result from the query? thanksTake a look at the "scope" attribute of the <sql:query> tag.
query.jsp:
<%@ taglib prefix="sql" uri="http://java.sun.com/jsp/jstl/sql" %>
<sql:setDataSource dataSource="jdbc/dbtest"/>
<sql:query var="items" scope="request" sql="SELECT * FROM homepagesubscriptions"/>
<jsp:forward page="test.jsp" />and then test.jsp:
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<table border="0" align="center" valign="top">
<c:forEach var="row" items="${items.rows}" begin = "0" end="10" >
<tr>
<td>
<img src="${row.imgurl}" width="100" height = "100"></a>
</td>
<tr>
</c:forEach>
</table> -
Hello, I wonder if anyone can help here. I want to run a sql query and then save the results of this query in a specific location.
I dont really know where to start. The db server is Sybase - but what I want to do is:
1) creating a report,
2) archive it with a sequential filename
3) then run another report and archive that with a new sequential filename.
Does anyone know the best way to go about this. It is quite urgent of course
many thanks
kevinSo you want to run a sql, create a report 123.txt and later on run another report named 124.txt etc..
Simple enough, You could go about this many ways. I would do it something on the lines of.
Create a file called LastNumber.dat (Contains the last file name like 123)
Read this file into a var run your process and when complete do var++ and over write that file you have with a new one containing the new value. (Only problem is) you must implement a good method to ensure you don't corrupt this file during the process. Hence the lost of where you left off at.
Or Be, Name each file like BLAH-#####.txt where ##### is the seq number. During your process first thing you do is create a File object and call its filelist() method. split the BLAH- and .txt off to obtain the ##### from the file name and stick it into an ArrayList. Run a sort method Collections.sort() on it and pick off the top file ###### and add one to it.
I hope these just give you some idea's of what you could do. These are not well thought out idea's, but they give you a good groud to start your thinking on.
I hope this helps.
-Richard Burton -
Storing the SQL Query results as XML
Hi All,
I have a proc to select all the data from emp table and insert into another table. For some reason it inserts only one column and one record.
I don't have any row limit or skip ...
CREATE OR REPLACE procedure Convert_Data_Into_XML1
as
-- Var Declartion
qryCtx DBMS_XMLGEN.ctxHandle;
result CLOB;
BEGIN
qryCtx := dbms_xmlgen.newContext('SELECT * from emp');
-- set the row header to be EMPLOYEE
DBMS_XMLGEN.setRowTag(qryCtx, 'Employee-ROW');
DBMS_XMLGEN.setRowsetTag(qryCtx, 'Employee-rowset');
LOOP
-- now get the result
result := DBMS_XMLGEN.getXML(qryCtx);
DBMS_OUTPUT.PUT_LINE ('In the Loop');
EXIT WHEN DBMS_XMLGEN.getNumRowsProcessed(qryCtx) = 0;
INSERT INTO temp_clob_tab VALUES (result);
END LOOP;
COMMIT;
--close context
DBMS_XMLGEN.closeContext(qryCtx);
exception
when others then
dbms_output.put_line(TO_CHAR(sqlerrm));
END;
Basically I got this sample proc from Oracle website. As per the website I should be able to store all the records from emp table.
How can I debug this.
Here is the output from SQLPLUS>
SQL> select result from temp_clob_tab;
RESULT
<?xml version="1.0"?>
<Employee-rowset>
<Employee-ROW>
<EMPNO>7369</EMPNO>
>>>>>>>>>>
Thanks in advance
SivaI am able to convert the SQL query output and I am able to store it in a XMLTYPE column.
But the code doesn't work when I took the same code and try to Implement inside a Trigger. The reason I am doing this is, when there is an update or delete, I want to store the whole record as a XMLTYPE doc (before and After). But the code compiles fine, but when I tried to update a record it gives error.
CREATE OR REPLACE TRIGGER INS_UPDDEV_EMP3_F
BEFORE UPDATE OR DELETE ON EMP
FOR EACH ROW
DECLARE
V_DBUSER VARCHAR2(50);
V_CHANGETYPE VARCHAR2(20) := 'INSERT' ;
QRYCTX DBMS_XMLGEN.CTXHANDLE ;
OLDVALUE XMLTYPE;
NEWVALUE XMLTYPE;
BEGIN
IF :OLD.EMPNO <> :NEW.EMPNO or DELETING then
---------- old Value
QRYCTX := DBMS_XMLGEN.NEWCONTEXT ('SELECT :OLD.EMPNO, :OLD.ENAME, :OLD.JOB, :OLD.MGR, :OLD.HIREDATE, :OLD.SAL, :OLD.COMM, :OLD.DEPTNO FROM EMP WHERE EMPNO=:OLD.EMPNO ');
DBMS_XMLGEN.SETROWTAG (QRYCTX, 'DEPTROW');
DBMS_XMLGEN.SETROWSETTAG(QRYCTX, 'DEPTSET');
OLDVALUE := XMLTYPE(DBMS_XMLGEN.GETXML(QRYCTX));
------------------------- new Value
QRYCTX := DBMS_XMLGEN.NEWCONTEXT ('Select * WHERE EMPNO=:NEW.EMPNO '); -- WHERE :OLD.EMPNO
DBMS_XMLGEN.SETROWTAG (QRYCTX, 'DEPTROW');
DBMS_XMLGEN.SETROWSETTAG(QRYCTX, 'DEPTSET');
NEWVALUE := XMLTYPE(DBMS_XMLGEN.GETXML(QRYCTX));
V_CHANGETYPE := 'UPDATE' ;
INSERT INTO ADM_RECAUDITHISTORY VALUES ('table emp', 'fIELD all', OLDVALUE, OLDVALUE,
V_CHANGETYPE , SYSDATE, 'TIGER TRIG');
commit;
END IF;
END;
I am getting the following error while updating the record.
>>>>
ERROR at line 1:
ORA-19206: Invalid value for query or REF CURSOR parameter
ORA-06512: at "SYS.DBMS_XMLGEN", line 83
ORA-06512: at "SCOTT.INS_UPDDEV_EMP3_F", line 13
ORA-04088: error during execution of trigger 'SCOTT.INS_UPDDEV_EMP3_F'
>>>>>
Is anyone knows why I am getting this error.
Thanks
Siva -
How to use SQL query result in DOS commands
Hi
Currently i am runnig below DOS commands manually
d:\apps\bin>TrueGridsCalc period="Aug 2010"
Now I want to write one batch file and schedule job on windows and make value of "period" to be dynamic. So to get that value i need to fetch it from DB
Steps which i am taking are
1. connect DB from command line (using SQLPLUS)
2. run query to fetch result
3.How to use query result in "period" parameter ?
I am good at step 1 and 2. Dnt know how to use query result in command to make it dynamic
Thank you
Sachin
Edited by: sachin.mali on Oct 26, 2010 4:39 PM
Edited by: sachin.mali on Oct 26, 2010 4:43 PMsachin.mali wrote:
Hi
Currently i am runnig below DOS commands manually
d:\apps\bin>TrueGridsCalc period="Aug 2010"
Now I want to write one batch file and schedule job on windows and make value of "period" to be dynamic. So to get that value i need to fetch it from DB
Steps which i am taking are
1. connect DB from command line (using SQLPLUS)
2. run query to fetch result
3.How to use query result in "period" parameter ?
I am good at step 1 and 2. Dnt know how to use query result in command to make it dynamic
Thank you
Sachin
Edited by: sachin.mali on Oct 26, 2010 4:39 PM
Edited by: sachin.mali on Oct 26, 2010 4:43 PMYOu'll have to have sqlplus spool the output to a file, then figure out some way of parsing that file. Too bad you're stuck with Windows. With any *nix you could do the file parsing with one line of code. -
How to get an sql query result to a textbox?
i am working with jdk1.4 and office 2003.
i need to run the following SQL Query: "SELECT max(BookId) as BookId FROM Books" where BookId is an autonumeric generated number obtained from the field autonumber in access 2003 database.
now, the result of this must be placed in a textbox.
does anyone knows how to do this?
I ve tried this but nothing happens and niether any error comes
st = con.createStatement (); //Creating Statement Object.
long bookNo; //Use for Comparing the Book's Id.
try { //SELECT Query to Retrieved the Record.
String q = "SELECT max(BookId) as BookId FROM Books";
ResultSet rs = st.executeQuery (q); //Executing the Query.
bookNo = rs.getLong ("BookId"); //Storing the Record.
bookNo =(bookNo+1);
txtBookId.setText (""+bookNo);
catch (SQLException sqlex) { }
does anyone knows how to do this?????plz help me out.
Thanks
AanchalHi Aanchal,
If an SQL error occurs now, you cannot see it in your code. You should do something with the exception you catch, e.g. printing it: sqlex.printStackTrace(), so that you can see if something goes wrong.
For your number, you should move the cursor in the resultset to the first row - either by: calling first( ) or next ( ), then you can retrieve your booknumber.
Best Regards,
Martijn -
Store SQL query results in db table
Hi,
I have a SQL query that produces a report table.
Is it possible to automatically store the query results (or the report table) as a db table - without interrupting the current report building proces?
Thanks,
Dave
Message was edited by:
Dave JudgeHi Dave,
You can also insert records into an existing table:
INSERT INTO TABLEB (colA, colB, colC, etc) SELECT valA, valB, valC, etc FROM VIEWA WHERE etc etc
This can be done during a page process that runs "Before Header" and you can base your report on the TABLEB. Obviously, you will need to maintain that table to ensure that it is only truncated where necessary, that one user doesn't try to access another user's data on that table and that each time your page is loaded it doesn't try to repopulate the table when you don't need it to.
Another possiblity is to use a collection - which is user session based
Andy -
SQL Query Result with Random Sorting
Hi Experts,
My Oracle Version : Oracle9i
I have three tables which are given below,
Table Name: check_team
team_id team_code
100 A
101 B
102 C
103 D
Table Name: check_product
product_id product_code
1 XXX
2 XYZ
Table Name: check_team_products
tprod_id tprod_team_id tprod_product_id
1 100 1
2 100 2
3 101 1
4 101 2
5 102 1
6 102 2
7 103 1
8 103 2
Required Output First Time:
team_id team_code product_id product_code
100 A 1 XXX
101 B 2 XYZ
102 A 1 XXX
103 B 2 XYZ
Required Output Second Time:
team_id team_code product_id product_code
100 B 2 XYZ
101 A 1 XXX
102 B 2 XYZ
103 A 1 XXXI need the result as Required Output specified above and also the result has to be random too.. Can someone help me in writing a SQL Query to get results as that?
Added Oracle VersionSo, is it something like this you want?
SQL> ed
Wrote file afiedt.buf
1 with check_team as (select 100 as team_id, 'A' as team_code from dual union all
2 select 101, 'B' from dual union all
3 select 102, 'C' from dual union all
4 select 103, 'D' from dual)
5 ,check_product as (select 1 as product_id, 'XXX' as product_code from dual union all
6 select 2, 'XYZ' from dual)
7 ,check_team_products as (select 1 as tprod_id, 100 as tprod_team_id, 1 as tprod_product_id from dual union all
8 select 2, 100, 2 from dual union all
9 select 3, 101, 1 from dual union all
10 select 4, 101, 2 from dual union all
11 select 5, 102, 1 from dual union all
12 select 6, 102, 2 from dual union all
13 select 7, 103, 1 from dual union all
14 select 8, 103, 2 from dual)
15 --
16 -- end of test data
17 --
18 select team_id, team_code, product_id, product_code
19 from (
20 select t.team_id, t.team_code, p.product_id, p.product_code
21 ,row_number() over (partition by team_id order by dbms_random.random()) as rn
22 from check_team t join check_team_products tp on (tp.tprod_team_id = t.team_id)
23 join check_product p on (p.product_id = tp.tprod_product_id)
24 )
25* where rn = 1
SQL> /
TEAM_ID T PRODUCT_ID PRO
100 A 2 XYZ
101 B 1 XXX
102 C 2 XYZ
103 D 1 XXX
SQL> /
TEAM_ID T PRODUCT_ID PRO
100 A 2 XYZ
101 B 1 XXX
102 C 2 XYZ
103 D 1 XXX
SQL> /
TEAM_ID T PRODUCT_ID PRO
100 A 1 XXX
101 B 2 XYZ
102 C 1 XXX
103 D 1 XXX -
Email SQL query results from powershell
I currently have a script that I run every half hour which runs an sql query, and takes the results, and emails them to a group of users. The script states how many faxes are in a faxmaker queue. Now, the powers that be would like to add additional
information, and I wanted to know how to include the additional information in my query. So, here is the script that is working. I've changed some information to protect the innocent.
$DATETIME = Get-Date -Format "MM-dd-yyyy [HH:mm:ss]";
##### CREATE A LOG FILE AND INSERT A LOG HEADING ;
$LOG_HEADING = "SHOW FLORIDA INBOUND FAX QUEUES RAN @: " + $DATETIME ;
Add-Content "E:\psh\LiveScripts\logs\SHOW-FLORIDA-INBOUND-FAX-QUEUE.TXT" $LOG_HEADING ;
# get sql dbname sample
#email variables
$EmailFrom = "[email protected]" ;
$EmailTo = "My Email List"
$SqlServer = "MY-SQL-SERVER"
$SqlCatalog = "FAXmakerArchive"
$SqlConnection = New-Object System.Data.SqlClient.SqlConnection
$SqlConnection.ConnectionString = "Server = $SqlServer; Database = $SqlCatalog; Integrated Security = True"
$SqlConnection.Open()
$SqlCmd = New-Object System.Data.SqlClient.SqlCommand
$SqlCmd.CommandText = "SELECT count (DISTINCT fax.ID) DATONA_BEACH_FAX_COUNT FROM
FM_FAXIN fax WITH (NOLOCK) LEFT OUTER JOIN T_FAX_REVIEW rvw WITH (NOLOCK) ON fax.ID = rvw.IDN_FAX WHERE (fax.RESULT LIKE '%SUCCESS%' OR (fax.RESULT NOT LIKE '%SUCCESS%' AND ATTACH_COUNT > 0)) AND
ISNULL(rvw.BOOL_IS_COMPLETE, 0) = 0 AND fax.LINE IN (SELECT LINE FROM T_LOCATION_FAX_LINE lne WITH (NOLOCK) WHERE lne.CDE_ACTIVE_FLAG = 1 AND lne.IDN_LOCATION =
3) AND fax.DATE > '2013-09-25' "
$SqlCmd.Connection = $SqlConnection
$NumberOfFlaInboundFaxes = $SqlCmd.ExecuteScalar()
$SqlConnection.Close()
if( $NumberOfFlaInboundFaxes -gt 29)
#Email Body
$EmailBody = @"
There are currently $NumberOfFlaInboundFaxes Faxes in the Florida Inbound Fax Queue ( )`n
Please Log in and help clear the Queue. Thank you. `n
`n`n`n
The people who recieved this email are: $EmailTo`n`n`n
From ApexAdmin/SystemScheduler
$EmailSubject = "There are " + $NumberOfFlaInboundFaxes + " faxes in the Inbound Florida Fax Queue. " + $DATETIME ;
#End of Email Body
#send mail via gmail through powersehll
$SMTPServer = "smtp.gmail.com"
$SMTPClient = New-Object Net.Mail.SmtpClient($SmtpServer, 587)
$SMTPClient.EnableSsl = $true
$SMTPClient.Credentials = New-Object System.Net.NetworkCredential("email user", "email password");
$SMTPClient.Send($EmailFrom, $EmailTo, $EmailSubject , $EmailBody)
Else
Write-Host "NO ALERT on $DATETIME `n" -foreground 'DARKGREEN' -background 'WHITE' ;
#Write-output "There are currently: " $NumberOfFlaInboundFaxes " Faxes in the Florida Fax Queue"
Write-Host "There are currently " $NumberOfFlaInboundFaxes " Files in the Florida fax queue" -foreground 'DarkBLUE' -background 'white'
Write-Host "SMTP Alert sent to " ( "$EmailTo" ).ToUpper() " on $DATETIME `n" -foreground 'DARKBLUE' -background 'WHITE' ;
write-Host "WROTE AN ENTRY TO THE LOGFILE.`n" -foreground 'DARKGREEN' -background 'WHITE'
Now, I'd like to also include this query... also changed information to protect the innocent.
SELECT u.IDN_USER,
u.NAM_LASDBUSER,
u.NAM_FIRSDBUSER,
r.NAM_ROLE,
COUNT(o.IDN_ORDER) ORDER_CNT,
COUNT(DISTINCT
o.IDN_CLIENT) CLIENDBCNT,
(SELECT IDN_ZONE FROM DBUSER_PREF p WHERE u.IDN_USER = p.IDN_USER) IDN_USER_ZONE
FROM DBORDER o WITH (NOLOCK)
INNER JOIN DBUSER u WITH (NOLOCK)
ON o.IDN_USER_CRTD = u.IDN_USER
INNER JOIN DBROLE r WITH (NOLOCK)
ON u.IDN_ROLE = r.IDN_ROLE
WHERE DATEDIFF(d, GETDATE(), o.DTE_RECORD_CRTD)>=0 AND DATEDIFF(d, GETDATE(), o.DTE_RECORD_CRTD)<=0
AND r.IS_INTERNAL_USER = 1
GROUP BY u.IDN_USER, u.NAM_LASDBUSER, u.NAM_FIRSDBUSER, r.NAM_ROLE, r.IS_INTERNAL_USER
ORDER BY u.NAM_LASDBUSER, u.NAM_FIRSDBUSER
Thank you in advance for any suggestions, links, etc, you can provide. I don't mind doing the heavy lifting, ie: research and reading, just needed to be pointed in the right directions.
JohnAs an example this is more readable but could be improved which would make your adding a section much easier.
$DATETIME = Get-Date -Format 'MM-dd-yyyy [HH:mm:ss]'
$LOG_HEADING = "SHOW FLORIDA INBOUND FAX QUEUES RAN @: " + $DATETIME;
Add-Content "E:\psh\LiveScripts\logs\SHOW-FLORIDA-INBOUND-FAX-QUEUE.TXT" $LOG_HEADING;
$sql = @'
SELECT count(DISTINCT fax.ID) DATONA_BEACH_FAX_COUNT
FROM FM_FAXIN fax WITH (NOLOCK)
LEFT OUTER JOIN T_FAX_REVIEW rvw WITH (NOLOCK) ON fax.ID = rvw.IDN_FAX
WHERE
fax.RESULT LIKE '%SUCCESS%' OR (
fax.RESULT NOT LIKE '%SUCCESS%' AND ATTACH_COUNT > 0
AND ISNULL(rvw.BOOL_IS_COMPLETE, 0) = 0
AND fax.LINE IN (SELECT LINE FROM T_LOCATION_FAX_LINE lne WITH (NOLOCK)
WHERE lne.CDE_ACTIVE_FLAG = 1 AND lne.IDN_LOCATION = 3) AND fax.DATE > '2013-09-25'
$template=@'
There are currently {0} Faxes in the Florida Inbound Fax Queue ( )
Please Log in and help clear the Queue. Thank you.
The people who recieved this email are: $EmailTo
From ApexAdmin/SystemScheduler
$subject= 'There are {0} faxes in the Inbound Florida Fax Queue. {1:MM-dd-yyyy [HH:mm:ss]}'
$EmailFrom='[email protected]'
$EmailTo = "My Email List"
$SqlServer = "MY-SQL-SERVER"
$SqlCatalog = "FAXmakerArchive"
#run query
$SqlConnection = New-Object System.Data.SqlClient.SqlConnection
$SqlConnection.ConnectionString = "Server = $SqlServer; Database = $SqlCatalog; Integrated Security = True"
$SqlConnection.Open()
$SqlCmd = New-Object System.Data.SqlClient.SqlCommand
$SqlCmd.CommandText = $sql
$SqlCmd.Connection = $SqlConnection
$NumberOfFlaInboundFaxes = $SqlCmd.ExecuteScalar()
$SqlConnection.Close()
# build email if needed
if($NumberOfFlaInboundFaxes -gt 29){
$EmailBody=$template -f $NumberOfFlaInboundFaxes
$EmailSubject = $subject -f $NumberOfFlaInboundFaxes,[DateTime]::Now
$SMTPServer='smtp.gmail.com"'
$SMTPClient=New-Object Net.Mail.SmtpClient($SmtpServer, 587)
$SMTPClient.EnableSsl = $true
$SMTPClient.Credentials = New-Object System.Net.NetworkCredential("email user", "email password");
$SMTPClient.Send($EmailFrom, $EmailTo, $EmailSubject , $EmailBody)
}else{
Write-Host "NO ALERT on $DATETIME `n" -foreground 'DARKGREEN' -background 'WHITE' ;
Write-Host "There are currently $NumberOfFlaInboundFaxes Files in the Florida fax queue" -foreground 'DarkBLUE' -background 'white'
Write-Host "SMTP Alert sent to $EmailTo on $DATETIME" -foreground 'DARKBLUE' -background 'WHITE' ;
write-Host 'WROTE AN ENTRY TO THE LOGFILE.' -foreground 'DARKGREEN' -background 'WHITE'
\_(ツ)_/ -
Query resulting Incorrect values
Hello ALL.
I need your suggestions on this issue.
I have a Query on top of multiprovider which is on top of 6 cubes. In the query one RKF is resulting wrong values for Unassigned WBS Element Hierarchy.
<u><b>RF: Forecast amount</b></u>
0amount, Version:01, Vtype:20,Company Code:100,Fiscyear=2008 and Posting Period=1-12.
Query resulting: 68,000 and Where as Multi prvider has only 2 rows satisfying the above Restrictions and giving 13,000.
These wrong values are only for Unassgined Nodes of WBS Element.(Rows) Other node values are correct.
I am not sure where it is getting these values?
Kindly suggest.
Thanks,
Geetha
<u></u>Can you chk if you have the values in the multiprovider?
-
SQL query result with HTML Data in output
Hello,
I have a SQL table , in one column I store HTML data. I need to query the table and get the HTML data in the columns that have 'HREF'. The output shows as grid on the sql management studio, however when I export it to excel, the HTML data does not get copied
correctly, since there are HTML tags etc.
How can I export the report correctly from SQL ?Hello,
The HTML data is stored in a column with datatype as nvarchar(max). Sample data in the column is shown below. It is with formatting etc and is rendered as is on the web page. the business wants to generate a quick report so that they can see the pages that
have links displayed. I can do that by querying the columns that have a 'HREF' in the text.
Can I get the exact HREF values using just sql query? There can be more than one links on a page.
Also, If I just want to copy the whole column and paste it on excel, how can I do that? If I copy the data below and paste, it does not get copied in one cell.. it spreads across multiple cells, so the report does not make any sense.
<br />
<table border="0" cellpadding="0" cellspacing="0" style="width: 431pt; border-collapse: collapse;" width="574">
<tbody>
<tr height="19" style="height: 14.25pt; ">
<td height="19" style="border: 0px blue; width: 431pt; height: 14.25pt; background-color: transparent;" width="574"><a href="https:"><u><font color="#0066cc" face="Calibri">ax </font></u></a></td>
</tr>
</tbody>
<colgroup>
<col style="width: 431pt; " width="574" />
</colgroup>
</table>
Maybe you are looking for
-
I am using final FCP 5.1.2 and OS 10.4.8 with the black magic deck link sp to acess beta SP. My problem is that when I try to capture DV via a fire wire it does not recognize the source. It does however control the device but no vidoe or audio comes
-
Multiple tc types on one scxi 1102
Does anybody know if you can use two different thermocouple types on one SCXI-1102 module? I need to measure both Type K and Type T thermocouples. I am using a SCXI 1303 connector block and plan to use the internal CJC. Thanks in advance doloop
-
JDBC-ODBC-Bridge connection to SQL Database
Hi guys I have a problem. I've made a little game which I want to put on my website. It has a highscore-list which I want to connect to my web host's database server to get the current list. I tried this with JDBC and got it to work locally but when
-
RA01 (Discount % on gross) condition type
Dear Sir I require some clarification with an example on the following When can I use this condition type(RA01) and what is the role of pricing procedure RM0001 assigned in it
-
I noticed on the Aperture camera page that the E-1 was a supported camera but there was no mention of any other model from Olympus even though the supported files include the Olympus file format. Does that mean any Olympus camera that shoots RAW is s