Actual comment in a stored procedure...?
I'm no DBA but we found this comment from one of the stored procedures in SM.. thoughts??
CREATE PROCEDURE [dbo].[p_SelectForTypeCache]
(@LanguageCode1 varchar(3),
@LanguageCode2 varchar(3),
@LastKnownMPLastModified datetime,
@LastKnownMPCacheRefreshTimestamp datetime
) AS
BEGIN
-- OMG IS THIS WRONG!!!
-- BUGBUG
-- HACK
SELECT [ImageReference].[ImageId], [ImageReference].[ReferenceId], [ImageReference].[ManagementPackId], [ImageReference].TimeAdded, [ImageReference].LastModified, SUBSTRING([EnumType].EnumTypeName, 39, 100) AS ImageCategory, [MPElementView].[MPElementName],
[ManagementPack].[ContentReadable]
END
It sounds like it might be a bug workaround. Perhaps there's a more efficient way of writing the procedure or feature that the developers didn't have time to implement before a given deadline.
The comment wording probably isn't great for PR, but you can find these kinds of "fix this", "todo", and "bug" comments in any large software system (whether you can read them yourself or not is usually up to the publisher).
Similar Messages
-
How can I automatically prepend comment blocks to stored procedures?
How can I automatically prepend comment blocks to stored procedures?
In my organization, the standard is to comment all stored procedures with a comment block that looks like this:
/*-- =============================================
-- Created by: <Owner>
-- Created date: 01/08/2012
-- Purpose: Inserts new setting value, code and description
-- Modifications:
-- Modified by: <Owner>
-- Modification date: 01/08/2012
-- Purpose: Inserts new setting value, code and description
-- =============================================*/Thanks.
select * from v$version;
BANNER
Oracle Database 11g Express Edition Release 11.2.0.2.0 - Production
PL/SQL Release 11.2.0.2.0 - Production
CORE 11.2.0.2.0 Production Edited by: xDeviates on 01-ago-2012 7:37
Edited by: xDeviates on 01-ago-2012 8:31Hi,
If I want to write a package called pk_fubar, I copy the following script and call it fubar.sql
-- ========== package_name.sql starts here ==========
-- Package_Name.sql
SPOOL &home_dir\package_name.lst
PROMPT . H H EEEE A DDDD
PROMPT . H H E A A D D
PROMPT . HHHHH EEE A A D D
PROMPT . H H E AAAAA D D
PROMPT . H H EEEEE A A DDDD
@@package_name_head
PROMPT . BBBB OOO DDDD Y Y
PROMPT . B B O O D D Y Y
PROMPT . BBBB O O D D Y
PROMPT . B B O O D D Y
PROMPT . BBBB OOO DDDD Y
@@package_name_body
SPOOL OFF
@@package_name_test
-- EXIT
-- ========== package_name_head.sql starts here ==========
CREATE OR REPLACE PACKAGE pk_package_name
AS
FUNCTION sign_in
( in_user_name IN VARCHAR2
, in_password_txt IN VARCHAR2
RETURN PLS_INTEGER
END pk_package_name;
SHOW ERRORS;
GRANT EXECUTE ON pk_package_name TO schema_name_some_role;
-- ========== package_name_body.sql starts here ==========
CREATE OR REPLACE PACKAGE BODY pk_package_name
AS
-- Procedures related to SCHEMA_NAME ...
-- 2012 July 23 -- Package started with proc_x. (Frank Kulash)
-- ** local procedures and variables **
-- ** x **
-- ** initialization section **
-- The following code is executed once per session, when the package is loaded.
BEGIN
set_var ( 'DT_FMT_TXT'
, 'YYYY-MM-DD HH24:MI:SS'
END pk_package_name;
SHOW ERRORS;
-- ========== package_name_test.sql starts here ==========
-- PACKAGE_NAME_TEST.SQL -- Test procedures in schema_name.pk_package_name
SET DOCUMENT OFF
SET SERVEROUTPUT ON SIZE 10000
ALTER SESSION SET NLS_DATE_FORMAT = 'DD-Mon-YYYY HH24:MI:SS';
SPOOL @@package_name_test.lst
PROMPT
PROMPT ***********************
PROMPT ** Testing x **
PROMPT ***********************
PROMPT
SPOOL OFFThen I replace package_name with fubar, and schema_name with the actual schema name. Finally, I cut off parts from the end to create fubar_test.sql, fubar_body.sql and fubar_head.sql. You could easily include a multi-line procedure comment template in this script. Every time you add a procedure or function, ciopy and paste that comment template, and then modify the copy. -
Do SQL pros write seperate stored procedures to handle Save and update operations?
hi friends,
Currently i'm bit confused with the industry standard of writing store procedures for save and update operations. I have sees people write separate stored procedure to handle save and update operations even they have to write complex queries. Also I have
seen people writing one store procedure to handle both Save and Update operations even when the queries are complicated. when I asked them why they do it, they said why should waste time on writing another query to update instead write one save store procedure
to handle all.
In here there are SQL Pros, Gurus, what would say about this?
what is the actual industry standard with stored procedure to perform save and update operations, do you write separate ones or do both in one?
thanks
I use Visual studio 2012 Ultimate and SQL server 2008 developer edition!>what is the actual industry standard with stored procedure to perform save and update operations
There is no industry standard. Guideline though you want to be happy with the sp-s; same for your peers.
As noted above the MERGE command is like a Swiss Army knife; it can perform INSERT, UPDATE & DELETE
in one (huge) statement.
Make sure you pick good names for the sp-s, document the parameters and comment the logic if any.
Format the stored procedure for readability:
http://www.sqlusa.com/sqlformat/
Kalman Toth Database & OLAP Architect
SELECT Query Video Tutorial 4 Hours
New Book / Kindle: Exam 70-461 Bootcamp: Querying Microsoft SQL Server 2012 -
Stored Procedure parameter (@Carrier) used in report and can't be set via code
I have a report that has regular Crystal parameters that I am setting correctly via code. However, one report actually uses one of the database parameters from the stored procedure that the report was created from. It is the only report like this and I'm using the same code in an attempt to set it's value. Although no error is thown, if I look at the parameter value in the IDE it is set correctly, but the field on the report just shows up blank. I have changed the way the report is created. Previously, I used the report.export method to create the actual file via a stored procedure. Now, I'm running the stored procedure first and creating a datatable. This allows me to execute the SP only once to see if it has data, because only then do I want to create the actual report. I'm using the SetDataSource method to pass the datatable into Crystal and then using the report.export method to create the report with data. Everything seems to work, except this stored procedure parameter (@Carrier) is not actually being populated to display on the report.
Not sure what to look at. Any suggestions?
Thanks.crpe32.dll is version 13.0.5.891. This was developed in VS2012 and VB.NET. I'm using ADO.Net to connect to a MS SQL Server database.
MainReport.SetDataSource(DTbl)
bRC = PopulateAllSubReports(MainReport)
If Not bRC Then Throw New Exception("Received an error in PopulateAllSubReports.")
bRC = PopulateCrystalParameters(MainReport, SP)
If Not bRC Then Throw New Exception("Received an error in PopulateCrystalParameters.")
'Actually create the output file.
bRC = ExportData(MainReport)
Private Function PopulateCrystalParameters(myReportDocument As ReportDocument, SP As ReportStoredProcedureCrystal) As Boolean
Dim myParameterFieldDefinitions As ParameterFieldDefinitions = Nothing
Dim myParameterFieldDefinition As ParameterFieldDefinition = Nothing, ParamValue As String = ""
Dim bRC As Boolean, Param As SqlParameter = Nothing
Try
myParameterFieldDefinitions = myReportDocument.DataDefinition.ParameterFields
'*********************Report Parameters***************************
For Each myParameterFieldDefinition In myParameterFieldDefinitions
myParameterFieldDefinition.CurrentValues.Clear()
Select Case myParameterFieldDefinition.ParameterFieldName.Trim.ToUpper
Case "@CARRIER"
If SP.DBParameters.ContainsKey("@CARRIER") Then
Param = SP.DBParameters("@CARRIER")
ParamValue = NullS(Param.Value).Trim
bRC = SetCurrentValueForParameterField(myParameterFieldDefinition, ParamValue)
If Not bRC Then Return False
End If
End Select
Next
Return True
Catch ex As Exception
GmcLog.Error("ReportKey = " & Me.ReportKey.ToString & ", " & ex.Message, ex)
Return False
End Try
End Function
Private Function SetCurrentValueForParameterField(myParameterFieldDefinition As ParameterFieldDefinition, submittedValue As Object) As Boolean
Dim currentParameterValues As ParameterValues = Nothing
Dim myParameterDiscreteValue As ParameterDiscreteValue = Nothing
Try
myParameterDiscreteValue = New ParameterDiscreteValue
myParameterDiscreteValue.Value = NullS(submittedValue).Trim
currentParameterValues = New ParameterValues
currentParameterValues.Add(myParameterDiscreteValue)
myParameterFieldDefinition.ApplyCurrentValues(currentParameterValues)
Return True
Catch ex As Exception
GmcLog.Error("ReportKey = " & Me.ReportKey.ToString & ", " & ex.Message, ex)
Return False
Finally
myParameterDiscreteValue = Nothing
currentParameterValues = Nothing
End Try
End Function
Private Function SetDBSourceForSubReport(mySubReport As ReportDocument) As Boolean
Dim myTables As Tables = Nothing, myTable As Table = Nothing, DTbl As DataTable, SP As StoredProcedure = Nothing
Try
myTables = mySubReport.Database.Tables
For Each myTable In myTables
Dim SPName As String = myTable.Location.Substring(0, myTable.Location.IndexOf(";"c))
SP = New StoredProcedure(ConnectionString, SPName, CommandType.StoredProcedure)
DTbl = SP.FillTable
mySubReport.SetDataSource(DTbl)
SP = Nothing
Next
Return True
Catch ex As Exception
GmcLog.Error("ReportKey = " & Me.ReportKey.ToString & ", " & ex.Message, ex)
Return False
Finally
If Not SP Is Nothing Then SP = Nothing
If Not myTable Is Nothing Then myTable = Nothing
If Not myTables Is Nothing Then myTables = Nothing
End Try
End Function
Private Function PopulateAllSubReports(myReportDocument As ReportDocument) As Boolean
Try
Dim mySections As Sections = myReportDocument.ReportDefinition.Sections
For Each mySection As Section In mySections
Dim myReportObjects As ReportObjects = mySection.ReportObjects
For Each myReportObject As ReportObject In myReportObjects
If myReportObject.Kind = ReportObjectKind.SubreportObject Then
Dim mySubreportObject As SubreportObject = CType(myReportObject, SubreportObject)
Dim subReportDocument As ReportDocument = mySubreportObject.OpenSubreport(mySubreportObject.SubreportName)
Dim bRC = SetDBSourceForSubReport(subReportDocument)
If Not bRC Then Return False
End If
Next
Next
Return True
Catch ex As Exception
GmcLog.Error("ReportKey = " & Me.ReportKey.ToString & ", " & ex.Message, ex)
Return False
End Try
End Function -
Calling pl/sql stored procedure from shell script ( kshell)
hello.,
i have written a stored procedure. i need to call this stored procedure from a unix shell script ( korn shell).
can anyone please help me how can i do it.actually there are 3 stored procedures. so my shell script has to call each stored procedure, execute it then go to next stored procedure execute it.
if by chance inbetween any stored procedure do not execute then the shell script has to tell me that this stored procedure failed to execute.
please help me in this.
thanks
madanSorry Madan,
Following is the complete solutiion:
!# /usr/bin/ksh
sqlplus -s user/pass@server << EOF > a.log
exec proc1;
exec proc2;
exec proc3;EOF
if [ $? -eq 0 ]
then
echo "\n Procedures completed successfully at `date`"
else
echo "!!! FAILED!!!"
echo "Details can be found in a.log File"
fi -
How to install Stored Procedures
Hi
We are creating a .net application. At the time of installation in client location, the installation should write some stored procedures to the existing oracle 8i database. Please guide us to do this. we are nowise in this.
Thanks
Lee1212There is no actual install process for stored procedure. Stored procedures are the so called stored program units, and are considered as regular Oracle objects that can be created with a regular DDL command (Data Definition Language) i.e. CREATE command. You must have suitable privileges to perform the action, otherwise an error will show up. Packages are composed of a package specification and a package body, which usually are written on two different files.
You are supposed to write or have a sql script on the third party side, who will perform the action. You must have a user with suitable privileges created by your administrator.
Once you have met all requirements, just issue the command to run the script. This script, as a de facto standard has a *.sql extension (in case both specification and body are in the same file) In case the specification and the body were written on different files, then as a de facto standard, the first file will have a *.pls extension, meanwhile the body will have a *.plb extension.
Usually, but not required, the package body is written in a wrapped format (some sort of encoding).
Run the script as previously directed. You can verify the existence of the recently created objects from the USER_OBJECTS view or from the DBA_OBJECTS (privileges are required to access dba_* views).
~ Madrid -
Error While Executing Stored Procedure - SAP BPC 5.0
Hi all
I have defined stored procedure 'EP2' in the account transformation rules and which runs fine with all the entities.
But when I filter particular entity which give no data extrace to the selections made instead of giving the comment:
0 rows created and update it gives the error below.
Kindly Help me out if any one has the idea of running stored procedure
Executing SPRUNCALCACCOUNT "[[FINANCE]],[[ACTUAL]],[[LC]],[[SPSCOPE_367693]],[[SPLOG_887033]],[[EP2]]"
SPRunCalcAccount Version 2.06
-ERR- CALC-070 No DATA Extract From FACT Table
Time to run stored procedure:2.8 sec.
Edited by: Harish Bysani Kodanda on Mar 14, 2008 8:46 AM
Edited by: Harish Bysani Kodanda on Mar 14, 2008 8:47 AM
Edited by: Harish Bysani Kodanda on Mar 14, 2008 8:48 AMYes, the business rules stored procedures surface an error if there is an empty data set to operate on.
-
I've just tried to "Submit Feedback" but the page just gives me an error which means nothing to anyone which says "You are not authorized to submit the feedback for this connection.". Why am I not authorised how do I become authorised etc
etc. Anyway :-)
I've trying to report that the stored procedure in Sql Server Replication in 12.0.2000 has an issue with data type lengths. This procedure sp_MSdetect_nonlogged_shutdown uses data lengths of nvarchar(2048) but the MSDB sysjobhistory table has a message field
length of 4000. Which causes the above stored procedure to crash.
Best Regards
RichardThis is the work around
1. Stop SQL Server service.
2. On command prompt run the following command to run the server in single user mode – be sure to replace the MSSQLSERVER with the actual instance name
C:\>”C:\Program Files\Microsoft SQL Server\MSSQL.1\MSSQL\Binn\sqlservr.exe” -sMSSQLSERVER -m
3. Connect to SQL server with SSMS as the server administrator
4. Run the following to change the database to the system resource database: “USE mssqlsystemresource”
5. Run the following to update the stored procedure (only change is to make NVARCHAR(4000))
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO
ALTER procedure [sys].[sp_MSdetect_nonlogged_shutdown]
@subsystem nvarchar(60),
@agent_id int
as
begin
declare @job_id binary(16)
declare @agent_name sysname
declare @message nvarchar(4000)
declare @retcode int
declare @runstatus int
declare @run_date int
declare @run_time int
declare @run_date_orig int
declare @run_time_orig int
declare @merge_session_id int
-- security check
-- only db_owner can execute this
if (is_member ('db_owner') != 1)
begin
raiserror(14260, 16, -1)
return (1)
end
-- Detect if the agent was shutdown without a logged reason
if UPPER(@subsystem collate SQL_Latin1_General_CP1_CS_AS) = 'SNAPSHOT'
begin
if exists (select runstatus from MSsnapshot_history where
agent_id = @agent_id and
runstatus <> 2 and
--CAC runstatus <> 5 and
runstatus <> 6 and
timestamp = (select max(timestamp) from MSsnapshot_history where agent_id = @agent_id))
begin
select @job_id = job_id, @agent_name = name from MSsnapshot_agents where id = @agent_id
end
end
else if UPPER(@subsystem collate SQL_Latin1_General_CP1_CS_AS) = 'LOGREADER'
begin
if exists (select runstatus from MSlogreader_history where
agent_id = @agent_id and
runstatus <> 2 and
--CAC runstatus <> 5 and
runstatus <> 6 and
timestamp = (select max(timestamp) from MSlogreader_history where agent_id = @agent_id))
begin
select @job_id = job_id, @agent_name = name from MSlogreader_agents where id = @agent_id
end
end
else if UPPER(@subsystem collate SQL_Latin1_General_CP1_CS_AS) = 'DISTRIBUTION'
begin
if exists (select runstatus from MSdistribution_history where
agent_id = @agent_id and
runstatus <> 2 and
--CAC runstatus <> 5 and
runstatus <> 6 and
timestamp = (select max(timestamp) from MSdistribution_history where agent_id = @agent_id))
begin
select @job_id = job_id, @agent_name = name from MSdistribution_agents where id = @agent_id
end
end
else if UPPER(@subsystem collate SQL_Latin1_General_CP1_CS_AS) = 'MERGE'
begin
if exists (select runstatus from dbo.MSmerge_sessions where
agent_id = @agent_id and
runstatus <> 2 and
--CAC runstatus <> 5 and
runstatus <> 6 and
session_id = (select top 1 session_id from dbo.MSmerge_sessions where agent_id = @agent_id order by session_id desc))
begin
select @job_id = job_id, @agent_name = name from dbo.MSmerge_agents where id = @agent_id
select top 1 @merge_session_id = session_id from dbo.MSmerge_sessions
where agent_id = @agent_id
order by session_id desc
end
end
else if UPPER(@subsystem collate SQL_Latin1_General_CP1_CS_AS) = 'QUEUEREADER'
begin
if exists (select runstatus from MSqreader_history where
agent_id = @agent_id and
runstatus <> 2 and
--CAC runstatus <> 5 and
runstatus <> 6 and
timestamp = (select max(timestamp) from MSqreader_history where agent_id = @agent_id))
begin
select @job_id = job_id, @agent_name = name from MSqreader_agents where id = @agent_id
end
end
-- If no job_id assume shutdown was logged properly
if @job_id is null
return 0
-- Get last message from SQL Agent History table
create table #JobHistory (
instance_id int NOT NULL,
job_id uniqueidentifier NOT NULL,
job_name sysname NOT NULL,
step_id int NOT NULL,
step_name nvarchar(100) NOT NULL,
sql_message_id int NOT NULL,
sql_severity int NOT NULL,
message nvarchar(4000) NOT NULL,
run_status int NOT NULL,
run_date int NOT NULL,
run_time int NOT NULL,
run_duration int NOT NULL,
operator_emailed sysname NULL,
operator_netsent sysname NULL,
operator_paged sysname NULL,
retries_attempted int NOT NULL,
server sysname NOT NULL
if @@error <> 0
return 1
-- Insert last history for step_id 2 (Agent running)
insert TOP(2) into #JobHistory exec sys.sp_MSreplhelp_jobhistory @job_id = @job_id, @step_id = 2,
@mode = 'FULL'
declare cursorHistory cursor local fast_forward for
select message,
run_status,
run_date,
run_time
from #JobHistory
order by run_date desc,
run_time desc,
instance_id asc
open cursorHistory
fetch cursorHistory into @message, @runstatus, @run_date, @run_time
select @run_date_orig = @run_date,
@run_time_orig = @run_time
while @@fetch_status <> -1
begin
-- as long as we are looking at the history for the same run
-- date and time then we should log all rows. there should
-- be 2 rows since we perform a TOP on exec sp_help_jobhistory
if @run_date_orig = @run_date
and @run_time_orig = @run_time
begin
-- Map SQL Agent runstatus to Replication runstatus
set @runstatus =
case @runstatus
when 0 then 6 -- Fail mapping
when 1 then 2 -- Success mapping
when 2 then 5 -- Retry mapping
when 3 then 2 -- Shutdown mapping
when 4 then 3 -- Inprogress mapping
when 5 then 0 -- Unknown is mapped to never run
end
-- If no message, provide a default message
-- Also overwrite all inprogress messages to be "See SQL Agent history log".
-- This is to prevent "Agent running. See monitor" to be logged into repl monitor.
-- In this case (the last job history message is InProgress), we know that
-- there have been failures of SQL Server Agent history logging.
-- In fact, the only possible "in progress" msg in SQL Agent job step
-- history for push jobs is "Agent running. See monitor". It is confusing that those
-- messages showed up in repl monitor.
if @message is null or @runstatus = 3
begin
raiserror(20557, 10, -1, @agent_name)
select @message = formatmessage(20557, @agent_name)
end
if UPPER(@subsystem collate SQL_Latin1_General_CP1_CS_AS) = 'SNAPSHOT'
exec @retcode = sys.sp_MSadd_snapshot_history @agent_id = @agent_id, @runstatus = @runstatus,
@comments = @message
else if UPPER(@subsystem collate SQL_Latin1_General_CP1_CS_AS) = 'LOGREADER'
exec @retcode = sys.sp_MSadd_logreader_history @agent_id = @agent_id, @runstatus = @runstatus,
@comments = @message
else if UPPER(@subsystem collate SQL_Latin1_General_CP1_CS_AS) = 'DISTRIBUTION'
exec @retcode = sys.sp_MSadd_distribution_history @agent_id = @agent_id, @runstatus = @runstatus,
@comments = @message
else if UPPER(@subsystem collate SQL_Latin1_General_CP1_CS_AS) = 'MERGE'
exec @retcode = sys.sp_MSadd_merge_history @agent_id = @agent_id, @runstatus = @runstatus,
@comments = @message, @called_by_nonlogged_shutdown_detection_agent = 1, @session_id_override = @merge_session_id
else if UPPER(@subsystem collate SQL_Latin1_General_CP1_CS_AS) = 'QUEUEREADER'
exec @retcode = sys.sp_MSadd_qreader_history @agent_id = @agent_id, @runstatus = @runstatus,
@comments = @message
if @@error <> 0 or @retcode <> 0
return 1
end
fetch cursorHistory into @message, @runstatus, @run_date, @run_time
end
close cursorHistory
deallocate cursorHistory
drop table #JobHistory
end
6. Return the system resource database to read-only – “alter database mssqlsystemresource set read_only”
7. Shutdown the instance – “shutdown”
8. Start the instance using the service as usual -
Passing dynamic parameter to stored procedure from CR formula?
Dear all,
I need to insert in some textboxes the right string based on the desired Language Code.
I crated a stored procedure in my db.
CREATE PROCEDURE MY_GET_TRANSLATION
@TextID nvarchar(8),
@LangCode int
This parameters are used as keys to get the Trans field.
I created a workshop formula: GetTranslation
Please, can someone suggest the correct statement to call my MY_GET_TRANSLATION stored procedure passing parameters?
I would like to call the GetTranslation formula from all my textboxes, passing the specific TextID value
and visualized the right translated string.
For example:
in my TEXT1 textbox, I would like to call the GetTranslation formula passing the parameters
TextID = "T000001"
and
LangCode = 13 (Italian language)
How can pass dynamic parameters to a formula?
How can pass dynamic parameters to a stored procedure from a CR formula?
Regards
EmanueleDear Jason,
I'm trying to modify a SAP B1 CR marketing report.
This CR marketing document is called by SAP B1 automatically passing the Document Number and Document Type.
The report uses the right SAP B1 tables to read the information of the header and rows of the document.
The language of the document is contained in a field of the header table
{MyMarketingDocTable.LanguageID}
I created a user table named "MyTranslationTable" where I added some strings in different langiages.
For example:
TexiID TextString LangID
T00001 Delivery 8
T00001 Consegna 13 (Italian translation)
T00002 Invoice 8
T00002 Fattura 13 (Italian translation)
In the header of the report I'd like, for example, to visualise the string "Consegna" if my document is a delivery in italian language.
I'd like to implement this method to translate all the textboxes (header, comments, etc.) based on the languageID of my document.
For each textboxes, in the CR designer statically I know what TextID I want to visualized but dinamically I need to pass to my stored procedure the right language. I'd like my report automatically gets the language at run-time. I don't want that when I press the Print-preview button in SAP B1, the report asks to prompt the languageID.
It already read the DocNum and DocType and it already filter the SAP B1 tables basing on the DocNum and DocType of the document. In this way it reads the right row in the SAP B1 table and in this way I can read all the fields of this row (also the languageID of the actual document).
Regards
Emanuele
Edited by: Emanuele Croci on Dec 3, 2010 9:03 AM -
Using stored procedures with dabasae controls
Hi. We have two questions.
Answer 1:
We are working with Sybase and we are trying to use stored procedures (SP) with databse controls but we don't know how to obtain SP's return. We can to use SP normally if that SP don't have any return. Next example works fine but "stored_procedure_name" actually returns an number (error code) and we need to obtain it:
* @jc:sql statement="{call stored_procedure_name (?)}"
Answer 2:
Do you know how to call SP dinamically? This mean to call an sql statemente where stored_procedure_name and its parameters could be pased as paremeters. That looks as:
* @jc:sql statement="{call {sql: spName} {sql: listOfParameters}}"
Thak you very much for your comments.
Regards.I have my entity manager setup in a singleton.
I'm finding it's costly to generate the emf, but if I don't close the em (enitity manager) and emf (entity manager factory) my open cursor count climbs until I exceed the max number of open cursors on the database (11g RAC)
I'm committing the connection, and uow, and closing the em at the end of each call.
But until I close the emf, the open cursors aren't released.
TransactionhistoryPkg tranPkg = new TransactionhistoryPkg(conn); //Class created over database package via JPublisher
tranPkg.transactionhistoryInsSp(insertTrans.getCardId()); // executes db package
tranPkg.closeConnection();
conn.commit();
uow.commit();
uow.getAccessor().decrementCallCount();
em.close();
Am I missing something really obvious here??
btw - I found this link helpful in troubleshooting the max cursors issue: https://support.bea.com/application_content/product_portlets/support_patterns/wls/InvestigatingORA-1000MaximumOpenCursorsExceededPattern.html -
I have a patient table in the SQL Server database. Clients connect to the database and checkout one of the patients and do some operations on it and save it afterwards.
Since multiple clients might access the patient at the same time. I wanted to implement pessimistic locking mechanism, So that if one client can acquire a lock to a particular patient at a time.
Also if one of the clients locks a particular patient and either crashes or closes the client application the lock should be released. In case of crash the lock should be released when we detect that the connection of client with the database is closed.
I found out that I could use sp_getapplock and sp_releaseapplock to
do achieve this and specify @LockOwner
= 'Session' when calling sp_getapplock,
this ensures that the lock is released once the database session with the client closes.
From the code, I call a stored procedure in database to acquire the lock. This acquires the lock correctly and if i close off the client app or the client app crashes the lock is released. This is behaving as I wanted it to.
The problem happens when I call another stored procedure which is supposed to release the lock. As soon as the stored procedure is entered the lock is released, before we even execute sp_releaseapplock
@patientId, @LockOwner = 'Session' the line which is actually supposed to release the lock.
I tried creating an empty stored procedure (just commented out
DECLARE @result int
EXEC @result = sp_releaseapplock @patientId, @LockOwner = 'Session'
This stored procedure still releases the lock I acquired using sp_getapplock.
I can't seem to understand why this is happening. It should only release when I explicitly call `sp_releaseapplock @patientId, @LockOwner = 'Session'``
CREATE PROCEDURE [dbo].[uspReleaseAppLock]
@patientId nvarchar(max), -- Patient ID
@ReturnValue int Output
AS
BEGIN
DECLARE @result int
EXEC @result = sp_releaseapplock @patientId, @LockOwner = 'Session'
SET @ReturnValue = @@SPID
END
Could someone tell me why this is happening. What am I missing here ? I checked that the session ids of both the stored procedures (for acquiring and releasing the lock) are same, so it dose not seem that a new session is being created by entity frame work
for each call to the stored procedure. Something else is going on which I am not able to comprehend. Any ideas ?Hi oalvi,
The Stored Procedure(SP) sp_getApplock initialed with "@LockOwner='Session'" is
session scoped. Your procedure
[dbo].[uspReleaseAppLock]
did the same work as you explicitly call "sp_releaseapplock @Resource = @patientId, @LockOwner='Session'", after the SP
uspReleaseAppLock
called or the current session ends, the lock released.
It doesn't make sense to call the uspReleaseAppLock to release the lock initialized in another session. If you try, you get the error like below, as I mentioned, the lock is session scoped.
"Cannot release the application lock (Database Principal: 'public', Resource: 'patient1') because it is not currently
held"
Regarding the same session ID you get from calling 2 SPs separately in Entity Framework(EF). As per my limitation knowledge on EF, If the maxsize of the project connection
pool equals 1, you may get the same session always.
Some cautions for sp_getApplock
Locks can be explicitly released with sp_releaseapplock. When an application calls sp_getapplock multiple times for the same lock resource, sp_releaseapplock must be called the same number of times to release the lock.
Due to the connection pool, the sessions may last long, that's what you need to take into account.
By the way, is there any reason that you have to use the sp_getApplock? What is the procedure doing that you cannot rely on SQL Servers build-in concurrency control mechanisms?
If you have any question, feel free to let me know.
Eric Zhang
TechNet Community Support -
How to pass the parameter values to the stored procedure from java code?
I have a stored procedure written in sqlplus as below:
create procedure spInsertCategory (propertyid number, category varchar2, create_user varchar2, create_date date) AS BEGIN Insert into property (propertyid, category,create_user,create_date) values (propertyid , category, create_user, create_date); END spInsertCategory;
I am trying to insert a new row into the database using the stored procedure.
I have called the above procedure in my java code as below:
CallableStatement sp = null;
sp = conn.prepareCall("{call spInsertCategory(?, ?, ?, ?)}");
How should I pass the values [propertyid, category, create_user, create_date) from java to the stored procedure?[i.e., parameters]
Kindly guide me as I am new to java..Java-Queries wrote:
I have a stored procedure written in sqlplus as below:FYI. sqlplus is a tool from Oracle that provides a user interface to the database. Although it has its own syntax what you posted is actually PL/SQL. -
Cannot Send Email Notification Using Stored Procedure.
Hi Friends,
I tried to execute this job scheduler...
begin
dbms_scheduler.create_job(
job_name => 'ILMS_JOB_SCHEDULE'
,job_type => 'PLSQL_BLOCK'
,job_action => 'begin ilms.check_reminder(); end; '
,start_date => SYSTIMESTAMP
,repeat_interval => 'FREQ=DAILY'
,enabled => TRUE
,end_date => NULL
,comments => 'Ilms job schedule for notification.');
end;
However, since the effect is too long I rescheduled the frequency to be every one minute in this set attribute...
BEGIN
DBMS_SCHEDULER.SET_ATTRIBUTE(
name => 'ILMS_JOB_SCHEDULE'
,attribute => 'repeat_interval'
,value => 'FREQ=MINUTELY;INTERVAL=1'
DBMS_SCHEDULER.DISABLE('ILMS_JOB_SCHEDULE');
DBMS_SCHEDULER.ENABLE('ILMS_JOB_SCHEDULE');
END;
Check Reminder is the stored procedure invoked by job scheduler to check values in database columns before sending email notification to the respective recipients' email address and also the format of the email notification to be sent to the recipients...
CREATE OR REPLACE PROCEDURE check_reminder AS
NO number;
CURSOR emp_cur is
select * from pergerakan_ks where TASK_FLAG=7 and TASK_STATUS='InProgress';
emp_rec emp_cur%rowtype;
email_to varchar2(200);
default_email varchar2(200);
mesg varchar2(4000);
no_kes varchar2(100);
subj varchar2(4000);
kpi number;
crlf VARCHAR2( 2 ):= CHR( 13 ) || CHR( 10 );
BEGIN
default_email:='@abc.com.my';
FOR emp_rec in emp_cur
LOOP
if emp_rec.PKS_TKH_TERIMA is null then
dbms_output.put_line('count day ' || round(sysdate - to_date(emp_rec.pks_tkh_hantar)) || crlf || crlf);
if round(sysdate - to_date(emp_rec.pks_tkh_hantar)) >3 then
email_to:=emp_rec.pks_penghantar_id||default_email;
select b.KS_BIL_NO into no_kes from kertas_siasatan b where b.KS_ID = emp_rec.pks_ks_id;
subj:='Reminder untuk Membuat Tindakan Bagi No Kes '||no_kes;
mesg:='Reminder untuk Membuat Tindakan Bagi No Kes '||no_kes;
dbms_output.put_line('Sending email to ' || email_to || ' subject: ' || subj);
dbms_output.put_line('update old pergerakan pks_id : '||emp_rec.pks_id);
update pergerakan_ks set task_status='Done' where pks_id=emp_rec.pks_id;
dbms_output.put_line('insert new pergerakan ks : ');
insert into pergerakan_ks(pks_id,pks_ks_id,pks_km_id,pks_penghantar_id,pks_tkh_hantar,
pks_penerima_id,pks_tkh_terima,task_name,task_owner,task_status,task_flag,fb_id)
values(pks_id_seq.nextval,emp_rec.pks_ks_id,emp_rec.pks_km_id,
emp_rec.pks_penghantar_id,sysdate,
null,
null,emp_rec.task_name,
emp_rec.pks_penghantar_id,
'InProgress',6,emp_rec.fb_id);
commit;
e_mail_message(email_to,email_to,subj,mesg);
end if;
end if;
if emp_rec.PKS_TKH_TERIMA is not null then
dbms_output.put_line('emp_rec.pks_km_id ' || emp_rec.pks_km_id || crlf);
select c.KM_KPI into kpi from keluar_masuk_ks c where c.KM_ID = emp_rec.pks_km_id;
no := round(sysdate - to_date(emp_rec.pks_tkh_terima))-kpi;
dbms_output.put_line('count day - kpi' || no || crlf);
dbms_output.put_line('kpi ' || kpi || crlf);
if no = 1 then
email_to:=emp_rec.pks_penghantar_id||default_email;
select b.KS_BIL_NO into no_kes from kertas_siasatan b where b.KS_ID = emp_rec.pks_ks_id;
subj:='Reminder untuk Membuat Tindakan Bagi No Kes '||no_kes;
mesg:='Reminder untuk Membuat Tindakan Bagi No Kes '||no_kes;
dbms_output.put_line('Sending email to ' || email_to || ' subject: ' || subj);
email_to:=emp_rec.task_owner||default_email;
subj:='Reminder untuk Membuat Tindakan Bagi No Kes '||no_kes;
mesg:='Reminder untuk Membuat Tindakan Bagi No Kes '||no_kes;
dbms_output.put_line('Sending email to ' || email_to || ' subject: ' || subj);
e_mail_message(email_to,email_to,subj,mesg);
e_mail_message(email_to,email_to,subj,mesg);
end if;
if no = 3 then
select b.KS_BIL_NO into no_kes from kertas_siasatan b where b.KS_ID = emp_rec.pks_ks_id;
email_to:=emp_rec.task_owner||default_email;
subj:='Reminder untuk Membuat Tindakan Bagi No Kes '||no_kes;
mesg:='Reminder untuk Membuat Tindakan Bagi No Kes '||no_kes;
dbms_output.put_line('Sending email to ' || email_to || ' subject: ' || subj);
e_mail_message(email_to,email_to,subj,mesg);
end if;
end if;
END LOOP;
END;
E_mail_message is the stored procedure invoked by the check_reminder to tell scheduler information of the connection and the email address of the recipients...
CREATE OR REPLACE procedure
e_mail_message
from_name in varchar2,
to_name in varchar2,
subject in varchar2,
message in varchar2
is
l_mailhost VARCHAR2(64);
l_from VARCHAR2(64);
l_to VARCHAR2(64);
crlf VARCHAR2( 2 ):= CHR( 13 ) || CHR( 10 );
l_mail_conn UTL_SMTP.connection;
mesg VARCHAR2( 4000 );
BEGIN
select a.SERVER into l_mailhost from email_setting a where a.SERVER is not null;
select a.USERNAME into l_from from email_setting a where a.SERVER is not null;
--UTL_SMTP.open_data(l_mail_conn);
mesg:= 'Date: ' || TO_CHAR( SYSDATE, 'dd Mon yy hh24:mi:ss' ) || crlf ||
'From: <'||l_from||'>' || crlf ||
'Subject: ' ||subject|| crlf ||
'To: '||to_name || crlf || '' || crlf ;
mesg:=mesg||message;
l_mail_conn := UTL_SMTP.open_connection(l_mailhost, 25);
UTL_SMTP.helo(l_mail_conn, l_mailhost);
UTL_SMTP.mail(l_mail_conn, l_from);
UTL_SMTP.rcpt(l_mail_conn, to_name);
UTL_SMTP.data(l_mail_conn, mesg);
UTL_SMTP.quit(l_mail_conn);
END;
I tried to execute to execute the e_mail_message procedure but received this error. Also, no notification sent to the email address...
ORA-29279: SMTP permanent error: 501 5.1.3 Invalid address
ORA-06512: at "SYS.UTL_SMTP", line 21
ORA-06512: at "SYS.UTL_SMTP", line 99
ORA-06512: at "SYS.UTL_SMTP", line 241
ORA-06512: at "ILMS.E_MAIL_MESSAGE", line 33
ORA-06512: at line 13
Please help so that I can receive the email notification into my email...thanks in advance for your time..user13281540 wrote:
ORA-29279: SMTP permanent error: 501 5.1.3 Invalid address
ORA-06512: at "SYS.UTL_SMTP", line 21
ORA-06512: at "SYS.UTL_SMTP", line 99
ORA-06512: at "SYS.UTL_SMTP", line 241
ORA-06512: at "ILMS.E_MAIL_MESSAGE", line 33
ORA-06512: at line 13This is not an Oracle error - this is the mail server saying "+hey, I don't like that e-mail address you are supplying, I'm not accepting it!+".
If you look at RFC821 (Request For Comments memo 821 describes the SMTP specifications), you'll see that the sender and recipient needs to be supplied in the format +<[email protected]>+, e.g. +<[email protected]>+.
I have found that not all SMTP servers are equal in this regard. Some may insist on the brackets around the address, some may not.
You need to confirm the format of the addresses you use in the "+MAIL FROM+" and "+RCPT TO+" commands.. and ensure that these formats are accepted by your SMTP server - and if not, change your code to use an acceptable format.
The easiest way to do this is using telnet - and interacting directly and manually with the server. SMTP is a clear text protocol and easy to use manually. Try it. It is the best way to test SMTP interaction and validate the approach and SMTP commands and arguments used by your code. -
Hello
I'm hoping that someone here might be able to help or point me in the right direction. Apologies for the long post.
Just to set the scene, I am a SQL Server DBA and have very limited experience with System Centre so please go easy on me.
At the company I am currently working they are complaining about very poor performance when running reports (any).
Quick look at the database server and CPU utilisation being a constant 90-95%, meant that you dont have to be Sherlock Holmes to realise there is a problem. The instance consuming the majority of the CPU is the instance hosting the datawarehouse and in particular
a stored procedure in the DWStagingAndConfig database called Staging.GroomDwStagingData.
This stored procedure executes continually for 2 hours performing 500,000,000 reads per execution before "timing out". It is then executed again for another 2 hours etc etc.
After a bit of diagnosis it seems that the issue is either a bug or that there is something wrong with our data in that a stored procedure is stuck in an infinite loop
System Center 2012 SP1 CU2 (5.0.7804.1300)
Diagnosis details
SQL connection details
program name = SC DAL--GroomingWriteModule
set quoted_identifier on
set arithabort off
set numeric_roundabort off
set ansi_warnings on
set ansi_padding on
set ansi_nulls on
set concat_null_yields_null on
set cursor_close_on_commit off
set implicit_transactions off
set language us_english
set dateformat mdy
set datefirst 7
set transaction isolation level read committed
Store procedures executed
1. dbo.p_GetDwStagingGroomingConfig (executes immediately)
2. Staging.GroomDwStagingData (this is the procedure that executes in 2 hours before being cancelled)
The 1st stored procedure seems to return a table with the "xml" / required parameters to execute Staging.GroomDwStagingData
Sample xml below (cut right down)
<Config>
<Target>
<ModuleName>TransformActivityDim</ModuleName>
<WarehouseEntityName>ActivityDim</WarehouseEntityName>
<RequiredWarehouseEntityName>MTV_System$WorkItem$Activity</RequiredWarehouseEntityName>
<Watermark>2015-01-30T08:59:14.397</Watermark>
</Target>
<Target>
<ModuleName>TransformActivityDim</ModuleName>
<WarehouseEntityName>ActivityDim</WarehouseEntityName>
<RequiredWarehouseEntityName>MTV_System$WorkItem$Activity</RequiredWarehouseEntityName>
<ManagedTypeViewName>MTV_Microsoft$SystemCenter$Orchestrator$RunbookAutomationActivity</ManagedTypeViewName>
<Watermark>2015-01-30T08:59:14.397</Watermark>
</Target>
</Config>
If you look carefully you will see that the 1st <target> is missing the ManagedTypeViewName, which when "shredded" by the Staging.GroomDwStagingData returns the following result set
Example
DECLARE @Config xml
DECLARE @GroomingCriteria NVARCHAR(MAX)
SET @GroomingCriteria = '<Config><Target><ModuleName>TransformActivityDim</ModuleName><WarehouseEntityName>ActivityDim</WarehouseEntityName><RequiredWarehouseEntityName>MTV_System$WorkItem$Activity</RequiredWarehouseEntityName><Watermark>2015-01-30T08:59:14.397</Watermark></Target><Target><ModuleName>TransformActivityDim</ModuleName><WarehouseEntityName>ActivityDim</WarehouseEntityName><RequiredWarehouseEntityName>MTV_System$WorkItem$Activity</RequiredWarehouseEntityName><ManagedTypeViewName>MTV_Microsoft$SystemCenter$Orchestrator$RunbookAutomationActivity</ManagedTypeViewName><Watermark>2015-01-30T08:59:14.397</Watermark></Target></Config>'
SET @Config = CONVERT(xml, @GroomingCriteria)
SELECT
ModuleName = p.value(N'child::ModuleName[1]', N'nvarchar(255)')
,WarehouseEntityName = p.value(N'child::WarehouseEntityName[1]', N'nvarchar(255)')
,RequiredWarehouseEntityName =p.value(N'child::RequiredWarehouseEntityName[1]', N'nvarchar(255)')
,ManagedTypeViewName = p.value(N'child::ManagedTypeViewName[1]', N'nvarchar(255)')
,Watermark = p.value(N'child::Watermark[1]', N'datetime')
FROM @Config.nodes(N'/Config/*') Elem(p)
/* RESULTS - NOTE THE NULL VALUE FOR ManagedTypeViewName
ModuleName WarehouseEntityName RequiredWarehouseEntityName ManagedTypeViewName Watermark
TransformActivityDim ActivityDim MTV_System$WorkItem$Activity NULL 2015-01-30 08:59:14.397
TransformActivityDim ActivityDim MTV_System$WorkItem$Activity MTV_Microsoft$SystemCenter$Orchestrator$RunbookAutomationActivity 2015-01-30 08:59:14.397
When the procedure enters the loop to build its dynamic SQL to delete relevant rows from the inbound schema tables it concatenates various options / variables into an executable string. However when adding a NULL value to a string the entire string becomes
NULL which then gets executed.
Whilst executing "EXEC(NULL)" would cause SQL to throw an error and be caught, executing the following doesnt
DECLARE @null_string VARCHAR(100)
SET @null_string = 'hello world ' + NULL
EXEC(@null_string)
SELECT @null_string
So as it hasnt caused an error the next part of the procedure is to move to the next record and this is why its caught in an infinite loop
DELETE @items WHERE ManagedTypeViewName = @View
The value for the variable @View is the ManagedTypeViewName which is NULL, as ANSI_NULLS are set to ON in the connection and not overridded in the procedure then the above statement wont delete anything as it needs to handle NULL values differently (IS NULL),
so we are now stuck in an infinite loop executing NULL for 2 hours until cancelled.
I amended the stored procedure and added the following line before the loop statement which had the desired effect and "fixed" the performance issue for the time being
DELETE @items WHERE ManagedTypeViewName IS NULL
I also noticed that the following line in dbo.p_GetDwStagingGroomingConfig is commented out (no idea why as no notes in the procedure)
--AND COALESCE(i.ManagedTypeViewName, j.RelationshipTypeViewName) IS NOT NULL
There are obviously other ways to mitigate the dynamic SQL string being NULL, there's more than one way to skin a cat and thats not why I am asking this question, but what I am concerned about is that is there a reason that the xml / @GroomingCriteria is incomplete
and / or that the procedures dont handle potential NULL values.
I cant find any documentation, KBs, forum posts of anyone else having this issue which somewhat surprises me.
Would be grateful of any help / advice that anyone can provide or if someone can look at their 2 stored procedures on a later version to see if it has already been fixed. Or is it simply that we have orphaned data, this is the bit that concerns most as I dont
really want to be deleting / updating data when I have no idea what the knock on effect might be
Many many thanks
AndyFirst thing I would do is upgrade to 2012 R2 UR5. If you are running non-US dates you need the UR5 hotfix also.
Rob Ford scsmnz.net
Cireson www.cireson.com
For a free SCSM 2012 Notify Analyst app click
here -
Simple stored procedure - select with an if statement, returning a cursor
Hi,
I'm trying to create a very simple stored procedure, but having never worked with them before I'm not quite sure what I'm doing wrong.
Here's my code:
create or replace
procedure contact_return(
v_contact_id IN varchar2,
p_cursor OUT SYS_REFCURSOR)
AS
begin
set sql_statement varchar2(4000) := '
SELECT URN,
FIRSTNAME,
LASTNAME,
TITLE,
CREATED_DT,
AREA_URN,
MOBILE,
WORK,
EMAIL,
ORG_NAME,
ADDRESS,
POSTCODE,
IN_USE
FROM CONTACT';
if v_contact_id is not null then
sql_statement := sql_statement || ' where urn = ' || v_contact_id;
end if;
open p_cursor for sql_statement;
end;
It's actually returning 2 errors:
Error(7,3): PL/SQL: SQL Statement ignored
Error(7,7): PL/SQL: ORA-00922: missing or invalid option
Which seem to be a problem with my set sql_statement line, but it looks correct to me?
Thanksrajendra wrote:
Dear User,
It is not allowed to declare a variable inside the PL/SQL block means after begin ( in your case line no 7 ).
Lot of errors in your code.
Tell me your exact requirement and what you want to do , after that I will be able to solve your problem.
Thanks,
Rajendra
Well, you can declare after the begin, though it'll be as part of an embedded code block e.g.
SQL> ed
Wrote file afiedt.buf
1 create or replace procedure contact_return(empno IN number
2 ,c OUT SYS_REFCURSOR
3 ) AS
4 begin
5 declare
6 sql_statement varchar2(4000) := '
7 select *
8 from emp
9 where empno = nvl(:1,empno)';
10 begin
11 open c for sql_statement using contact_return.empno;
12 end;
13* end;
SQL> /
Procedure created.
SQL> var x refcursor
SQL> exec contact_return(7788,:x);
PL/SQL procedure successfully completed.
SQL> print x;
EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO
7788 SCOTT ANALYST 7566 19-APR-1987 00:00:00 3000 20
so, it is allowed, as long as it's coded correctly.
Maybe you are looking for
-
Hiding a subview called in a main view in WEBDYNPRO Application
Hello Experts, I have a scenario in which i am calling a subview inside a main view. I have created a main view in which:- 1. List of reportee to the manager logged in is getting displayed in the form of a table. 2. When we select any row of this tab
-
Error- "Unable to capture video..."
What is the solution to allow video capture in the preferred WMV mode. I know AVI mode works but compression sucks. Plus, my laptop was always able to capture vid in WMV until recently. Now i get this error!!!!!!!!!!! Pls advice on this error: "Unabl
-
'Server error' when trying to set up a new apple id on the new ipod touch...
I cant set up a new apple ID on my new ipod touch 'due to server error' and I would like to make a new @icloud.com email address, so I don't think I can set up my new id on the computer... Any help appreciated. Thanks.
-
How can I close my iPhoto on my MacBook Air?
I had tried to import my photos to my mac book from my iPod, i tried to stop the import but wasn't patient enough with it so i unplugged my iPod and i checked on it later and my photos weren't there. As a result of my being inpatient i can't close th
-
Unable to open ant file using JDeveloper
I am using JDeveloper 10.1.3 production (version 10.1.3.0.4 build 3673) and I am having difficulty understanding the way ant build files are handled by this version. I would like to open ant files (build.xml) just like any other XML file so that I ca