T-sql store PROC explanation
create table #chartData(
ChgText [varchar](500) NOT NULL,
ChgCount [int] NULL,
[Sort] [int] NOT NULL,
[PartcTot] [int] NULL,
PercentageOfTotal decimal(6,3)
declare @partcTot int;
declare @SQLString nvarchar(4000), @ParamDefinition nvarchar(500);
declare @NewLine char(2)
select @partcTot = [frdmrpt].[fn_pha_total_participants](default);
set @NewLine=char(13)+char(10)
set @SQLString =
N'insert into #chartData (ChgText,ChgCount,Sort,PartcTot,PercentageOfTotal)' + @NewLine
set @SQLString = @SQLString +
N'select t.ChgText, c.TypeCount, t.Sort, ' + cast(@partcTot as nvarchar) + N' as PartcTot, (frdmrpt.fn_pha_percent(c.TypeCount,'
set @SQLString = @SQLString +
cast(@partcTot as nvarchar) + N')/100.0) as PercentageOfTotal' + @NewLine
set @SQLString = @SQLString +
N'from [frdmrpt].[wt_rpt_pha_pw_Rdy2ChgLevels] t inner join (' + @NewLine
set @SQLString = @SQLString +
N' select d.' + @HRADetail_Column + N' as ChgType, COUNT(*) as TypeCount' + @NewLine
set @SQLString = @SQLString +
N' from [frdmrpt].[wt_rpt_pha_pw_Member] m join [frdmrpt].[wt_rpt_pha_pw_HRADetail2] d on d.UserID = m.UserID' + @NewLine
set @SQLString = @SQLString +
N' group by d.' + @HRADetail_Column + @NewLine
set @SQLString = @SQLString +
N') c on t.ChgType = lower(c.ChgType) order by t.Sort' + @NewLine
--print @SQLString;
exec sp_executesql @SQLString;
select ChgText,ChgCount,Sort,PartcTot,PercentageOfTotal from #chartData
end
GO
Can someone explain the code to me using comment especially what is going on in the
set @SQLString =
-- @partcTot value will be computed by function - [fn_pha_total_participants]
SELECT @partcTot = [frdmrpt].[fn_pha_total_participants](DEFAULT);
--Below statments will form a SQL INSERT statement into @SQLString
-- @NewLine variable will act as new line/pressing Enter key. That is why @NewLine is used at the end of line in below statements
SET @NewLine = CHAR(13) + CHAR(10)
-- Below will form INSERT INTO Table(<<ColumnList>>) statement
SET @SQLString = N'insert into #chartData (ChgText,ChgCount,Sort,PartcTot,PercentageOfTotal)' + @NewLine
-- PercentageOfTotal column is calculated here
SET @SQLString = @SQLString + N'select t.ChgText, c.TypeCount, t.Sort, ' + cast(@partcTot AS NVARCHAR) + N' as PartcTot, (frdmrpt.fn_pha_percent(c.TypeCount,'
SET @SQLString = @SQLString + cast(@partcTot AS NVARCHAR) + N')/100.0) as PercentageOfTotal' + @NewLine
-- wt_rpt_pha_pw_Rdy2ChgLevels table has inner join with table - (wt_rpt_pha_pw_Member which has self join again)
SET @SQLString = @SQLString + N'from [frdmrpt].[wt_rpt_pha_pw_Rdy2ChgLevels] t inner join (' + @NewLine
SET @SQLString = @SQLString + N' select d.' + @HRADetail_Column + N' as ChgType, COUNT(*) as TypeCount' + @NewLine
SET @SQLString = @SQLString + N' from [frdmrpt].[wt_rpt_pha_pw_Member] m join [frdmrpt].[wt_rpt_pha_pw_Member] d on d.UserID = m.UserID' + @NewLine
SET @SQLString = @SQLString + N' group by d.' + @HRADetail_Column + @NewLine
SET @SQLString = @SQLString + N') c on t.ChgType = lower(c.ChgType) order by t.Sort' + @NewLine
-- Uncomment below print statement to see what is your final SQL statement formed
-- print @SQLString;
-- Above SQLString is executed and data is inserted into #chartData
EXEC sp_executesql @SQLString;
-- At the end your SP selects the data from #chartData
SELECT ChgText
, ChgCount
, Sort
, PartcTot
, PercentageOfTotal
FROM #chartData
GO
-- You also need to declare @HRADetail_Column variable
-Vaibhav Chaudhari
Similar Messages
-
Pass parameters to sql store proc?
Is it possible to pass parameters from Crystal Report to sql store proc? I know it will prompt for paramters if the report is built based on a parameterized store proc. I am NOT talking about these parameters. I still want user to be able to select parameter values from dropdowns and use them as the procedure parameters.
Reason for my question is I don't want the store proc to create a table having all records then crystal makes report by filtering. The all-record table could grow huge very quickly as more data is put in.
Thank you very much.Hi Peter
Follow these steps:
A. Following steps applies to the main procedure:
1. Create a main report which accepts the same fields as you want to pass to the stored procedure. (Note that this main report is not based off the procedure that you want to execute. Just get the data that you want to pass to the procedure. We will call the procedure in the subreport.)
2. Now create the no. of dynamic parameters that you want your user to choose the data from in the main report. (Lets assume that the user will select a single value.)
B. Following section applies to the subreport:
1. Add a subreport to the main report. This subreport will be based off your procedure. This will automatically add up the stored procedure parameters to the subreport.
2. Take care that in the procedure you define the datatype of the parameters same as the field's data type that you want to pass to the procedure. This will show up your stored procedure parameters while subreport linking.
3. Now link the main report to the subreport with each parameter. Uncheck the "Select data based on" dialog box while linking each parameter.
Hope this post solves your problem. i am sorry for sounding descriptive.
Regards
Nikhil Sabnis -
To convert the "IBM DB2 Store Procs written in C" to Oracle PL-SQL
Hi, Is it possible to convert the "IBM DB2 Store Procs written in C" to Oracle PL-SQL. If you have any info, PL do let me know. Thanks in advance.
EG :
/* SMG Stored Procedures */
/* DB2 Stored Procedure: OrganisationExists */
/* Linkage: SIMPLE (no NULLs permitted) */
/* Load module name: SMGEC00 */
/* Purpose: DELETE FROM SSE_LOOKUP_MAP */
/* to run. */
/* Parameters: argvÃ1¨ short - return error code - OUT */
/* argvÃ2¨ char - return error message - OUT */
/* argvÃ3¨ char - BLEID - IN */
/* Reason for edit Date Who */
/* Initial version 09/04/03 Arockia */
#pragma runopts(plist(os))
#include <stdlib.h>
#include <string.h>
void main (int argc, char *argvè)
EXEC SQL INCLUDE SQLCA;
EXEC SQL BEGIN DECLARE SECTION;
char bleid??(12??);
EXEC SQL END DECLARE SECTION;
/* Set defaults for error code (argvÃ1¨) and error message (argvÃ2¨) */
strcpy(argv??(2??)," ");
*(int *)argv??(1??) = 0;
strcpy(bleid,argv??(3??));
EXEC SQL
DELETE FROM SSE_LOOKUP_MAP
WHERE BLEID = :bleid;
/* Set error code to record status of last SQL command */
*(int *)argv??(1??) = SQLCODE;
return;For this program, you could do some thing like:
SQL> CREATE TABLE sse_lookup_map(BLEID varchar2(10));
Table created.
SQL> CREATE or replace PROCEDURE test(p_bleid_in IN varchar2)
2 AS
3 BEGIN
4 DELETE FROM sse_lookup_map
5 WHERE BLEID = p_bleid_in;
6 END;
7 /
Procedure created.
SQL> ed
Wrote file afiedt.buf
1* INSERT INTO sse_lookup_map values('test1')
SQL> /
1 row created.
SQL> ed
Wrote file afiedt.buf
1* INSERT INTO sse_lookup_map values('test2')
SQL> /
1 row created.
SQL> SELECT * FROM sse_lookup_map;
BLEID
test1
test2
2 rows selected.
SQL> EXEC test('test1')
PL/SQL procedure successfully completed.
SQL> SELECT * FROM sse_lookup_map;
BLEID
test2
1 row selected.
SQL> -
Getting an error from calling a store proc
this is my code calling a store proc. i got all oracle 8i
drivers imported.
package FMISBean;
import java.sql.*;
import oracle.jdbc.driver.*;
public class getrecordj
public static void main(String [] args){
//global variables
Connection conOrcl=null;
String ProjectID ="222700-";
CallableStatement C_TPRO_J=null;
ResultSet R_TPRO_J = null;
try{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
conOrcl=DriverManager.getConnection("jdbc:odbc:FMISORCL","FMIS_USER","FMIS123");
try{
String SQL ="{ ? = call getJrecord(?) }";
C_TPRO_J = conOrcl.prepareCall(SQL);
//assign the ? to the argument passed
C_TPRO_J.registerOutParameter(1,OracleTypes.CURSOR);
C_TPRO_J.setString(2,ProjectID);
//execute the query
C_TPRO_J.executeQuery();
R_TPRO_J = (ResultSet) C_TPRO_J.getObject(1);
//looping through the resultSet
while (R_TPRO_J.next()){
//create an instance of the class
// JavaBeans JItems = new JavaBeans();
// set it to the Bean
System.out.println(R_TPRO_J.getString(1));
System.out.println(R_TPRO_J.getString(2));
System.out.println(R_TPRO_J.getString(3));
System.out.println(R_TPRO_J.getString(4));
System.out.println(R_TPRO_J.getString(5));
System.out.println(R_TPRO_J.getString(6));
//JItems.setexistingLane(R_TPRO_J.getInt(3));
// JItems.setproposed_lane(R_TPRO_J.getInt(4));
// JItems.setcomnt(R_TPRO_J.getString(5));
// JItems.setcomntType(R_TPRO_J.getString(6));
//add the object to the vector
// V_itemsJ.addElement(JItems);
}catch(SQLException w){
System.out.println(w.getMessage());
}}catch(Exception S){
//returning the vector
// return V_itemsJ;
//closing bracets
the store proc works fine if i test it in sql plus but when i call it from the page i get a dos window error
[oracle][orant]:line 1, colunm 13
PLS: expression is of wrong type
line 1 , colunm 7
PL/SQL: statement ignored
any ideas please would help?Here are some examples to reference:
http://www.javaalmanac.com/egs/java.sql/CallFunction.html
http://www.javaalmanac.com/egs/java.sql/CallProcedure.html
DesQuite -
Getting data stored in ref cursor ( got from store proc in oracle) to excel sheet)
Hey, I am trying to Get data stored in ref cursor ( got from store proc in oracle) to excel sheet in a virtual folder using ssis.
I am getting errors and cant do it. If anyone can help meHi Nabin000,
The Oracle stored procedure doesn't work with SSIS source adapters such as OLE DB Source because the data provider doesn't provide metadata for the source adapter. To achieve your goal, you can use a Script Component as source to call
the Oracle stored procedure by using System.Data.OracleClient OracleDataReader, and get the rows and add them to the pipeline buffer. For more information, please see:
http://social.msdn.microsoft.com/Forums/sqlserver/en-US/1d0b3a1b-8792-469c-b0d1-f2fbb9e9ff20/dump-oracle-ref-cursor-into-ms-sql-staging-table-using-ssis
http://social.msdn.microsoft.com/Forums/sqlserver/en-US/fcdaa97e-8415-4c3e-8ffd-1ad45b590d57/executing-an-oracle-stored-procedure-from-ssis?forum=sqlintegrationservices
http://msdn.microsoft.com/en-us/library/system.data.oracleclient.oracledatareader(VS.90).aspx
Regards,
Mike Yin
TechNet Community Support -
BPEL process to Insert XML into DB using pl/sql stored proc
Hi,
We have created a BPEL process in which we are taking input request and store it into Oracle Database using PL/SQL proc.
We have been unsuccessful in doing so because the data stored in table has root element missing.
Has any body done this (insert xml into DB using pl/sql stored proc) successfully ?
We can so this successfully if we do not use stored procedure and store data directly in table.
RegardsI have done this, stored it as a CLOB.
Also I received the payload as an opaque schema, so I had to convert the message from binary into string.
This way the root element doesn't get removed.
cheers
James -
Hi folks, how do you write a store proc to return all tyre Speeds if no Speeds are selected, it won’t work with
IS NULL!
I have tried the following
@Speed = ' ' and kind of works i.e. the first search work perfectly, but when you change one of the other
dropdown list you get all the same results regardless of what you have selected, it’s like the other dropdowns lists don’t filter the data after the first search!
SQL
WHERE Width
= @Width and Product.Profile
= @Profile and Product.Diamete
= @Diamete and Product.Speed
= @Speed or @Speed
= ' '
and Suppliers.SupplierDistrict
= LEFT(@CustPostcode,2)
ORDER
BY Product.ProductUnitSalePrice
ASC
ASP
<asp:DropDownList
ID="DropDownList1"
runat="server"
DataSourceID="SqlDataSource1"
DataTextField="Width"
DataValueField="Width"
Height="27px"
style="margin-left:
0px"
Width="99px"
AppendDataBoundItems="True">
<asp:ListItem
Text="Width"
Value=""
/>
</asp:DropDownList>
<asp:DropDownList
ID="DropDownList2"
runat="server"
DataSourceID="SqlDataSource3"
DataTextField="Profile"
DataValueField="Profile"
Height="27px"
Width="97px"
AppendDataBoundItems="True">
<asp:ListItem
Text="Profile"
Value=""
/>
</asp:DropDownList>
<asp:DropDownList
ID="DropDownList3"
runat="server"
DataSourceID="SqlDataSource4"
DataTextField="Diamete"
DataValueField="Diamete"
Height="29px"
Width="97px"
AppendDataBoundItems="True">
<asp:ListItem
Text="Diamete"
Value
=""
/>
</asp:DropDownList>
<asp:DropDownList
ID="DropDownList4"
runat="server"
DataSourceID="SqlDataSource5"
DataTextField="Speed"
DataValueField="Speed"
Height="29px"
Width="99px"
AppendDataBoundItems="True">
<asp:ListItem
Text="Select All"
Value=" "
/>
</asp:DropDownList>
Bruceythis?
WHERE Width = @Width
and Product.Profile = @Profile
and Product.Diamete = @Diamete
and (Product.Speed = @Speed
or COALESCE(@Speed,'') = '')
and Suppliers.SupplierDistrict = LEFT(@CustPostcode,2)
ORDER BY Product.ProductUnitSalePrice ASC
and set default value as blank at your front end
ie
<asp:DropDownList ID="DropDownList4" runat="server" DataSourceID="SqlDataSource5" DataTextField="Speed"DataValueField="Speed" Height="29px" Width="99px" AppendDataBoundItems="True">
<asp:ListItem Text="Select
All" Value="" />
</asp:DropDownList>
Please Mark This As Answer if it helps to solve the issue Visakh ---------------------------- http://visakhm.blogspot.com/ https://www.facebook.com/VmBlogs -
Schedule a store proc to run with different values
Hi ALL ,
I have a store Proc i need to schedule it using the sql agent that i can do but the requirement is to exec the same store proc for different values at same time .
like for eg i need to run the below same store proc for 3 different values at the same time.
exec getIPs 'US'
exec getIPs 'IND'
exec getIPs 'UK'
So for instance time is 02:30 am .
The Same Store Proc should exec for values like US,IND & UK . If the exec for one of the values fail it should still continue .
Like for eg if by chance due to some reason US fails it should move to next value IND in short continue with the exec.
These values US,IND,Uk am getting from a table called Countries .
Kindly help with this requirement.
Thanks
PriyaI am unable to test but you can try something like this,
DECLARE @COUNTRYID INT
SET @COUNTRYID = 1WHILE @COUNTRYID <= (SELECT MAX(COUNTRY_ID) FROM COUNTRY)
BEGIN
DECLARE @COUNTRY_CODE VARCHAR
BEGIN TRY
SELECT @COUNTRY_CODE = COUNTRY_CODE FROM COUNTRY WHERE COUNTRY_ID = @COUNTRYID
EXEC getIPs @COUNTRY_CODE
END TRY
BEGIN CATCH
INSERT INTO [dbo].[ERROR_LOG]
SELECT
GETDATE(),
ERROR_NUMBER() AS ErrorNumber
,ERROR_SEVERITY() AS ErrorSeverity
,ERROR_STATE() AS ErrorState
,ERROR_PROCEDURE() AS ErrorProcedure
,ERROR_LINE() AS ErrorLine
,ERROR_MESSAGE() AS ErrorMessage
END CATCH;
SET @COUNTRYID = @COUNTRYID + 1
END
Regards, RSingh -
How to send sortorder info to Store Proc
Hi
I have a Store Proc in SQL Server
Now i want to give the Sort Order dynamically for this Store
Proc.
When i am trying to send the SortOrder, in the query it is
saying that i cant give the parameter.
It is forcing me to give field names directly.
i cant able to give the Order by dynamically.
how can i do this.?
i need to change the Order By dynamically in Store Proc.
i can send the paramter to Store Proc, but its not accespting
in the query.Try this stored procedure.
CREATE PROCEDURE [dbo].[myProcedure]
@OrderParam VARCHAR(20)
AS
Declare @sQuery as VARCHAR(100)
SET @sQuery = 'select * from myTable order by ' +
CAST(@OrderParam AS VARCHAR(15))
EXEC(@sQuery)
GO
Thanks
Sankalan
(www.mindfiresolutions.com) -
DropDown List Problem for Dynamic Store Proc Parameter in SAP B1 8.8
I am working with the crystal report 2008 in SAP B1 8.8 and the report is used the Store Proc for retrieving data. As i need to show a list of Documnet No (DOCNUM) from Sales Order (ORDR) and Purchase Order (OPOR) for the users to select, i use the Dynamic Parameter as for the Store Proc parameter (@Contno), However, the drop down list can be shown fine in Crystal Report, but cant be shown in "Report Selection Criteria" while opening the Crystal Report through SAP B1.
Therefore, can anyone tell me how to add the dynamic drop down list (cause the documnet no list will be changed very frequently) in the SAP B1 8.8 "Report Selection Criteria" screen.
Thanks!!Classic Crystal Reports and Classic SAP connectivity questions
Classic Crystal Reports and Classic SAP connectivity questions -
Can we call a Java Stored Proc from a PL/SQL stored Proc?
Hello!
Do you know how to call a Java Stored Proc from a PL/SQL stored Proc? is it possible? Could you give me an exemple?
If yes, in that java stored proc, can we do a call to an EJB running in a remote iAS ?
Thank you!For the java stored proc called from pl/sql, the example above that uses dynamic sql should word :
CREATE OR REPLACE PACKAGE MyPackage AS
TYPE Ref_Cursor_t IS REF CURSOR;
FUNCTION get_good_ids RETURN VARCHAR2 ;
FUNCTION get_plsql_table_A RETURN Ref_Cursor_t;
END MyPackage;
CREATE OR REPLACE PACKAGE BODY MyPackage AS
FUNCTION get_good_ids RETURN VARCHAR2
AS LANGUAGE JAVA
NAME 'MyServer.getGoodIds() return java.lang.String';
FUNCTION get_plsql_table_A RETURN Ref_Cursor_t
IS table_cursor Ref_Cursor_t;
good_ids VARCHAR2(100);
BEGIN
good_ids := get_good_ids();
OPEN table_cursor FOR 'SELECT id, name FROM TableA WHERE id IN ( ' | | good_ids | | ')';
RETURN table_cursor;
END;
END MyPackage;
public class MyServer{
public static String getGoodIds() throws SQLException {
return "1, 3, 6 ";
null -
Item Type Based on PL/SQL stored proc causing errors
I am getting the following error when I add this item type based on a pl/sql stored proc that generates html based on the stored proc... the stored proc returns find but the other porlets get Error Message in there headers and in the porlet content I get:
Error: The listener returned the following Message: 503 Service Unavailable....
I also get the same error if I click on a link that is generated from my stored proc for the entire page I get the error:
Error: The listener returned the following Message: 503 Service Unavailable
and get nothing else returned...Greetings
I suggest you take a look at the following page and have a look on how to create portlets. Since the PL/SQL PDK allows you to create your own portlets inside the Oracle Database there should be no problem for creating the content inside a portlet the way you want it.
http://www.oracle.com/technology/products/ias/portal/pdk.html
Best regards
Johan -
URGENT!! Generating XML in a PL/SQL stored proc
Hi,
I need to generate XML from a PL/SQL stored proc.
I need to do it in Oracle 7.3.4 as well as 8.1.6 databases.
I need to have my own defined tags in the xml.
Say I have the table Person like
Person (
id number,
fname varchar2(40),
lname varchar2(40)
I need a stored proc will will select * from Person and output the data in XML form as
<Person Names>
<Employee>
<First Name personid="<<value from id field>>">
<<value from fname field>>
</First Name>
<Last Name>
<< value from lname field>>
</Last Name>
</Employee>
</Person Names>
I want to minimise hard coding also.
how can I do this ? any pointers ?
Thanks in advance, Hari
nullHi,
We are not having a Web Agent here. So i am unable to use PLSXML utility.
I installed XSU and is now able to create the XML, but with the table attribute names as the tags. So
1. Is there a way I can transform this XML to another XML with custom tags ( using an XSL ) in a PL/SQL procedure ?
2. Is there a way I can install and use PLSXML without the web agent ?
Thanks, Hari -
Arrays to pl/sql stored proc.
How can I send a java array
to a pl/sql stored proc.
I've understood that I have to something like this
ArrayDescriptor desc = ArrayDescriptor.createDescriptor(<sql_type_name>, conn);
ARRAY newArray = new ARRAY(desc, conn, java_array);
But what do I use as sql_type_name ?
/guha
nullI trust you have tried using java.sql.array datatype. This is the SQL3 datatype supported by the 8.1.6 drivers.
You would find detailed pointers at http://technet.oracle.com/tech/java/jroadmap/jdbc/listing.htm
Narayan.
null -
I have a table table1 with 20 columns and with ID as primary key.
I have another table 'check_result' which is having 'id' column.
I have written a store proc to check data and if failed write the id to 'check_result' table.
My store proc look like
CREATE OR REPLACE function fn_check(id number)
insert into check_result(id,column_name)
select id,'<column_naame>' from table1 where .....
union
select id,'<column_naame>' from table1 where .....
union
select id,'<column_naame>' from table1 where .....
Insertion is happening as above with union and where condition differ in each case.
Is there any better way to do this in store proc?896277 wrote:
Insertion is happening as above with union and where condition differ in each case.
Is there any better way to do this in store proc?Almost certainly. But unless you tell us more precisely what you're trying to achieve we're not going to be able to advise you.
Cheers, APC
Maybe you are looking for
-
HttpURLConnection and DataInputStream
I posted this in the Conventional & Interruptable IO forum, but thought it might be better off here.... I'm having a strange issue with this piece of code. The input stream coming in is quite predictable and I know that this loop will only iterate tw
-
Need help with settings....
My podcast was pulled for some reason from iTunes and they have told me to resubmit it but before I do I have to do this: Change the title and link fields of your RSS feed to something other than what they are now. Please can someone tell me what tha
-
Combining iDVD projects into one.
I have a few videos I burned from iMovieHD to iDVD 5 and now I want to combine them in pairs on one DVD, using a master menu that lets you select which video you want to watch. How can I do this? I dont have the iMovie files anymore and I didn't burn
-
Delete site in Adobe Business Catalyst
How can I delete a SITE create in Adobe Business Catalyst, I have a Creative Cloud account.
-
Error : LDAP Error code 32 - in shared services export operation
Hi everyone ! I m using MS Active Directory in my Shared services for external authentication. while exporting provisioning for all users against project:applications , it is not working Trace error is : 2010-05-26 16:43:58,988 Export : Root cause :