Handling iteration in SQL
Hi
I have a requirement where, given a contract (site) and part number I need to find the preferred supplier.
I had asked previously on this forum and thought I had be3en given a working solution with connect by prior and use of nocycle.
However, my data example was not good enough to test all scenarios, or at least enough scenarios.
I have a supplier table, which has a vendor number and an acquisition site.
I also have a purchase part supplier table which has for a given contract and part number, vendor number and whether the supplier is a primary vendor for that contract/part number.
In essence, for a given contract and part number I need to return the preferred vendor number.
However, there may be a few iterations to get that, because where the acquisition site for a supplier is not blank, I need to then use this as a link for to get the next supplier.
As usual, example helps, I think.
Consider this data:
Supplier:
Vendor_no Acquisition_site
1000 UK1
1001 UK3
1002 UK1
1003 blank
1004 UK2
1005 UK1
1006 UK2
1007 blank
1008 blank
Purchase_Part_Supplier:
Contract Part_no Vendor_no Primary_Vendor_db
UK1 A 1000 N
UK1 A 1001 N
UK1 A 1002 Y
UK2 A 1001 Y
UK3 A 1000 N
UK4 A 1006 Y
UK1 B 1004 Y
UK2 B 1001 Y
UK3 B 1007 Y
UK4 B 1008 YThis can be created as:
with
supplier as (
select 1000 vendor_no, 'UK1' acquisition_site from dual UNION ALL
select 1001, 'UK3' from dual UNION ALL
select 1002, 'UK1' from dual UNION ALL
select 1003, null from dual UNION ALL
select 1004, 'UK2' from dual UNION ALL
select 1005, 'UK1' from dual UNION ALL
select 1006, 'UK2' from dual UNION ALL
select 1007, null from dual UNION ALL
select 1008, null from dual
purchase_part_supplier as (
select 'UK1' contract, 'A' part_no, 'N' primary_vendor_db, 1000 vendor_no from dual UNION ALL
select 'UK1', 'A', 'N', 1001 from dual UNION ALL
select 'UK1', 'A', 'Y', 1002 from dual UNION ALL
select 'UK2', 'A', 'Y', 1001 from dual UNION ALL
select 'UK3', 'A', 'N', 1000 from dual UNION ALL
select 'UK4', 'A', 'Y', 1006 from dual UNION ALL
select 'UK1', 'B', 'Y', 1004 from dual UNION ALL
select 'UK2', 'B', 'Y', 1001 from dual UNION ALL
select 'UK3', 'B', 'Y', 1007 from dual UNION ALL
select 'UK4', 'B', 'Y', 1008 from dual
)I create a single list by joining the data as follows:
select s.vendor_no, s.acquisition_site, pps.contract, pps.part_no
from supplier s, purchase_part_supplier pps
where s.vendor_no=pps.vendor_no(+) and primary_vendor_db(+)='Y'This generates a list like this (I believe!):
vendor_no acquisition_site contract part_no
1000 UK1
1001 UK3 UK2 A
1001 UK3 UK2 B
1002 UK1 UK1 A
1003 blank
1004 UK2 UK1 B
1005 UK1
1006 UK2 UK4 A
1007 blank UK3 B
1008 blank UK4 BWhere I need to find the preferred vendor number for contract UK4, part number B the acquisition site for UK4/B is blank, so the vendor number is 1008 (the last row is the data set)
For contract UK2, part number B, the acquisition site (for contract UK2, part number B) is UK3 so we try again with this combination.
The acquisition site (for contract UK3, part number B) is blank and the vendor number is 1007 so this is returned.
However, to cater for bad data, consider where we look for contract UK1 and part number A. The acquisition site is UK1 which is the same as the contract, so this would create an infinite loop. Therefore we need to abort as such.
Also, consider contract UK3, part number A. There is no row at all for this, so again, abort accordingly.
The following scenarios are, to my knowledge the required results.
Starting Result
Cont Part
UK1 A Returns vendor_no 1002, acquisition_site UK1. Since the acquisition_site = contract this is infinite cycle, so abort as 'infinite cycle'.
UK2 A Returns vendor_no 1001, acquisition_site UK3.
UK3 A No row found, abort as 'no primary supplier found'.
UK3 A No row found, abort as 'no primary supplier found'.
UK4 A Returns vendor_no 1006, acquisition_site UK2.
UK2 A Returns vendor_no 1001, acquisition_site UK3.
UK3 A No row found, abort as 'no primary supplier found'.
UK1 B Returns vendor_no 1004, acquisition_site UK2.
UK2 B Returns vendor_no 1001, acquisition_site UK3.
UK3 B Returns vendor_no 1007, acquisition_site blank. Return 1007 as vendor number.
UK2 B Returns vendor_no 1001, acquisition_site UK3.
UK3 B Returns vendor_no 1007, acquisition_site blank. Return 1007 as vendor number.
UK3 B Returns vendor_no 1007, acquisition_site blank. Return 1007 as vendor number.
UK4 B Returns vendor_no 1008, acquisition_site blank. Return 1008 as vendor number.Can this be done or will I have to resort to PL/SQL?
Thanks
Martin
Well, I believe I have cracked it!
with
supplier as (
select 1000 vendor_no, 'UK1' acquisition_site from dual UNION ALL
select 1001, 'UK3' from dual UNION ALL
select 1002, 'UK1' from dual UNION ALL
select 1003, null from dual UNION ALL
select 1004, 'UK2' from dual UNION ALL
select 1005, 'UK1' from dual UNION ALL
select 1006, 'UK2' from dual UNION ALL
select 1007, null from dual UNION ALL
select 1008, null from dual
purchase_part_supplier as (
select 'UK1' contract, 'A' part_no, 'N' primary_vendor_db, 1000 vendor_no from dual UNION ALL
select 'UK1', 'A', 'N', 1001 from dual UNION ALL
select 'UK1', 'A', 'Y', 1002 from dual UNION ALL
select 'UK2', 'A', 'Y', 1001 from dual UNION ALL
select 'UK3', 'A', 'N', 1000 from dual UNION ALL
select 'UK4', 'A', 'Y', 1006 from dual UNION ALL
select 'UK1', 'B', 'Y', 1004 from dual UNION ALL
select 'UK2', 'B', 'Y', 1001 from dual UNION ALL
select 'UK3', 'B', 'Y', 1007 from dual UNION ALL
select 'UK4', 'B', 'Y', 1008 from dual
select nvl(return_value,default_value) return_value from
select 1 lnk, decode(CONNECT_BY_ISCYCLE,1,'**DataCyc', decode(acquisition_site, null, to_char(vendor_no,999999), '**DataMiss')) return_value
from
select s.vendor_no, s.acquisition_site, pps.contract, pps.part_no
from supplier s, purchase_part_supplier pps
where s.vendor_no=pps.vendor_no(+) and primary_vendor_db(+)='Y'
) q
where CONNECT_BY_ISCYCLE=1 or CONNECT_BY_ISLEAF=1
start with contract='UK3' and part_no='A'
connect by nocycle
prior acquisition_site=contract and prior part_no=part_no
(select 1 dftlnk, '**DataMiss' default_value from dual)
where dftlnk=lnk(+)
Similar Messages
-
Configure no. of session handled for same sql
hi, experts,
hi, if there is one report (only fire 1 sql by this report).
if only one internet explorer to run this report , it use 3 minutes to get it.
I use 3 internet explorers to run the same report but not running the report at the same time.
firstly, I run the report on first internet explorer.
then after 10 seconds, I run the report on 2nd internet explorer.
then after 10 seconds, I run the report on 3rd internet explorer.
after result on all internet explorer came, I check the sessions on the "Manage Sessions"
there are 2 sessions for same report.
How to configure no. of session handled for same sql on OBIEE?
thank you very much!shipon_97 wrote:
Here I see that at a particular time of the database , the number of session from v$session is "271" where as the number of session in the "v$resource_limit" is "280" . Here I get some differ among these parameters .
Would anybody plz tell why the no of sessions differ between v$session and v$resource_limit parameters .
The v$session views shows current sessions (which change rapidly), while the v$resource_limit shows the maximum resource utilization, like a high-water mark.
http://download-east.oracle.com/docs/cd/A97630_01/server.920/a96536/ch3155.htm -
Using FOR .. LOOP counter in handling of PL/SQL procedures with nest. table
Hi all!
I'm learning PL/SQL on Steve Bobrovsky's book (specified below sample is from it) and I've a question.
In the procedure of specified below program used an integer variable currentElement to get reference to the row of nested table of %ROWTYPE datatype.
Meanwhile, the program itself uses a common FOR .. LOOP counter i.
DECLARE
TYPE partsTable IS TABLE OF parts%ROWTYPE;
tempParts partsTable := partsTable();
CURSOR selectedParts IS
SELECT * FROM parts ORDER BY id;
currentPart selectedParts%ROWTYPE;
currentElement INTEGER;
PROCEDURE printParts(p_title IN VARCHAR2, p_collection IN partsTable) IS
BEGIN
DBMS_OUTPUT.PUT_LINE(' ');
DBMS_OUTPUT.PUT_LINE(p_title || ' elements: ' || p_collection.COUNT);
currentElement := p_collection.FIRST;
FOR i IN 1 .. p_collection.COUNT
LOOP
DBMS_OUTPUT.PUT('Element #' || currentElement || ' is ');
IF tempParts(currentElement).id IS NULL THEN DBMS_OUTPUT.PUT_LINE('an empty element.');
ELSE DBMS_OUTPUT.PUT_LINE('ID: ' || tempParts(currentElement).id || ' DESCRIPTION: ' || tempParts(currentElement).description);
END IF;
currentElement := p_collection.NEXT(currentElement);
END LOOP;
END printParts;
BEGIN
FOR currentPart IN selectedParts
LOOP
tempParts.EXTEND(2);
tempParts(tempParts.LAST) := currentPart;
END LOOP;
printParts('Densely populated', tempParts);
FOR i IN 1 .. tempParts.COUNT
LOOP
IF tempParts(i).id is NULL THEN tempParts.DELETE(i);
END IF;
END LOOP;
FOR i IN 1 .. 50
LOOP
DBMS_OUTPUT.PUT('-');
END LOOP;
printParts('Sparsely populated', tempParts);
END;
/When I've substituted an INTEGER global variable with such FOR .. LOOP counter, an APEX have returned an error "ORA-01403: no data found".
DECLARE
TYPE partsTable IS TABLE OF parts%ROWTYPE;
tempParts partsTable := partsTable();
CURSOR selectedParts IS
SELECT * FROM parts ORDER BY id;
currentPart selectedParts%ROWTYPE;
PROCEDURE printParts(p_title IN VARCHAR2, p_collection IN partsTable) IS
BEGIN
DBMS_OUTPUT.PUT_LINE(' ');
DBMS_OUTPUT.PUT_LINE(p_title || ' elements: ' || p_collection.COUNT);
FOR i IN 1 .. p_collection.COUNT
LOOP
DBMS_OUTPUT.PUT('Element is ');
IF tempParts(i).id IS NULL THEN DBMS_OUTPUT.PUT_LINE('an empty element.');
ELSE DBMS_OUTPUT.PUT_LINE('ID: ' || tempParts(i).id || ' DESCRIPTION: ' || tempParts(i).description);
END IF;
END LOOP;
END printParts;
BEGIN
FOR currentPart IN selectedParts
LOOP
tempParts.EXTEND(2);
tempParts(tempParts.LAST) := currentPart;
END LOOP;
printParts('Densely populated', tempParts);
FOR i IN 1 .. tempParts.COUNT
LOOP
IF tempParts(i).id is NULL THEN tempParts.DELETE(i);
END IF;
END LOOP;
FOR i IN 1 .. 50
LOOP
DBMS_OUTPUT.PUT('-');
END LOOP;
printParts('Sparsely populated', tempParts);
END;
/When I've tried to handle this code in SQL*Plus, the following picture have appeared:
Densely populated elements: 10
Element is an empty element.
Element is ID: 1 DESCRIPTION: Fax Machine
Element is an empty element.
Element is ID: 2 DESCRIPTION: Copy Machine
Element is an empty element.
Element is ID: 3 DESCRIPTION: Laptop PC
Element is an empty element.
Element is ID: 4 DESCRIPTION: Desktop PC
Element is an empty element.
Element is ID: 5 DESCRIPTION: Scanner
Sparsely populated elements: 5
DECLARE
ERROR at line 1:
ORA-01403: no data found
ORA-06512: at line 14
ORA-06512: at line 35What's wrong in code(or what I have not understood)? Help please!942736 wrote:
What's wrong in code(or what I have not understood)? Help please!First code. You have collection of 10 elements:
1 - null
2 - populated
3 - null
4 - populated
5 - null
6 - populated
7 - null
8 - populated
9 - null
10 - populated
Then you delete null elements and have 5 element collection
2 - populated
4 - populated
6 - populated
8 - populated
10 - populated
Now you execute:
printParts('Sparsely populated', tempParts);Inside procedure you execute:
currentElement := p_collection.FIRST;
This assingns currentElement value 2. Then procedure loops 5 times (collection element count is 5). Element 2 exists. Inside loop procedure executes:
currentElement := p_collection.NEXT(currentElement);
which assigns currentElement values 4,6,8,10 - all existing elements.
Now second code. Everything is OK until you delete null elements. Again we have:
2 - populated
4 - populated
6 - populated
8 - populated
10 - populated
Again you execute:
printParts('Sparsely populated', tempParts);Now procedure loops 5 times (i values are 1,2,3,4,5):
FOR i IN 1 .. p_collection.COUNT
Very first iteration assingns i value 1. And since collection has no element with substript 1 procedure raises no data found.
SY. -
Handling DST in SQL Query for UCCX Custom Report
We wrote all custom reports for one of the call centers using our UCCX deployment. One problem we see we will hit in the future is DST. We suggested they use UTC but they wanted to see the call data based off of EST timezone. Right now we are okay because we use -5 to get the correct data but come March we are wondering how to address the issue. What options do we have? How are other people handling DST with the SQL queries for custom reporting? I see that the HR client will determine this based off of the local computer time then gives you the option to use UTC. We have all of our queries in an Excel document that the customer just needs to open and select Refresh All to update their data.
Thanks"case-when" statements are evaluated in order.
so you must do something like this:
SELECT
CASE WHEN <is not number>THEN 'N'
CASE WHEN <is greater than 0>THEN 'Y'
Now "<is greater than 0>" will always have number for input, can't get "not number" error there.
See this thread:
Re: regular expression: integer is between N..M
Edited by: CharlesRoos on May 27, 2010 5:03 AM -
How to handle EXTENDED Views SQL 2000 to Oracle Migration
Hi All,
I am in the process of migrating SQL server 2000 database to Orcle databse. I would like to know how to handle the views created in SQL server with Extended clause.
See below for example for SQL 2000 view.
create view "Order Details Extended" AS
SELECT "Order Details".OrderID, "Order Details".ProductID, Products.ProductName,
"Order Details".UnitPrice, "Order Details".Quantity, "Order Details".Discount,
(CONVERT(money,("Order Details".UnitPrice*Quantity*(1-Discount)/100))*100) AS ExtendedPrice
FROM Products INNER JOIN "Order Details" ON Products.ProductID = "Order Details".ProductID
Thanks in advance for your reply.
RameshRamesh
The Workbench has a problem with spaces in identifiers which will be fixed in a later release.
Apart from that large drawback the view should work ok. [The parser handles convert and aliases]
Turloch -
Error Handling in the SQL Trigger 2008 R2
Hi ,
I need some guidance in setting up error handling process in the table trigger. I have created a trigger on source database table and it load data to target table whenever there are any changes in last update date of source database ( given code below).
Problem : sometime I am getting error message ( like unique Index , data length mismatch etc) and my trigger don’t work and rollback the entire transaction.
Requirement : If there is an error with the insertion, I would like to move that error-inducing record into an error table . Any guidance much appreciate. thanks!
/****** Object: Trigger Defination ******/
USE [MPSAIntegration]
GO
SET
ANSI_NULLS ON
GO
SET
QUOTED_IDENTIFIER ON
GO
/*Description: Trigger to insert Asset details into Siebel Table*/
ALTER
TRIGGER [dbo].[trg_INS_INTO_CX_PRODPROF_STG]
ON [MPSAIntegration].[dbo].[CustomerProductLines]
AFTER INSERT,UPDATE
AS
/****** Get the current Timestamp,Max of SR_NUM from Target table and LastRun time from dbo.TIME ******/
DECLARE @currtime
DATETIME,
@SR_NUM
INT,
@Last_Run
DATETIME
SELECT @currtime
= (SELECT
CURRENT_TIMESTAMP)
SELECT @SR_NUM
= (select
max(Sr_Num)
from dbo.SerialNum
WHERE Entity='PROD')
SELECT @Last_Run
= (SELECT LastRun
from [MPSAIntegration].[dbo].[TIME]
where ENTITY =
'PROD')
BEGIN
SET
NOCOUNT ON;
SET
XACT_ABORT ON;
/***** Update dbo.SerialNum Table *****/
UPDATE dbo.SerialNum
SET Sr_Num = @SR_NUM+1
where Entity='PROD';
/***** Insert into [dbo].[CX_PRODPROF_STG] table *****/
INSERT
INTO [ntscrmdbdev].[SiebelDB].[dbo].[CX_PRODPROF_STG]
([ROW_ID]
,[CREATED]
,[CREATED_BY]
,[LAST_UPD]
,[LAST_UPD_BY]
,[MODIFICATION_NUM]
,[CONFLICT_ID]
,[LOAD_STATUS]
,[SR_NUM]
,[INFO_CAPTURE_DATE]
,[ADDRESS_NAME]
,[CUSTOMER_CODE]
,[DESCRIPTION]
,[PRODUCT]
,[SERVER_NAME]
,[STATUS]
,[CANCEL_DATE],
[SEQUENCE_ID])
SELECT
CAST(CUSTOMERCODE
AS NVARCHAR(8))+CAST(@SR_NUM
AS NVARCHAR(7))
,Current_Timestamp
,'dbo'
,Current_Timestamp
,Current_User
,0
,'N'
,'Not Processed'
,CAST(@SR_NUM
AS NVARCHAR(15))
,InfoCaptureDate
,(SELECT CUST.CUSTOMERNAME
FROM CUSTOMERS CUST where CUST.CustomerCode
= I.CustomerCode)
,CustomerCode
,ProductLine
,ProductLine
,ServerName
,'ACTIVE'
,TerminationDate
,1
FROM INSERTED I
/****** Update the LastRun in dbo.TIME ******/
UPDATE [MPSAIntegration].[dbo].[TIME]
SET LastRun
= @currtime
WHERE ENTITY
= 'PROD';
ENDThe first choice is stored procedure. Trigger should be last resort.
Related links:
http://stackoverflow.com/questions/884334/tsql-try-catch-transaction-in-trigger
http://www.sqlservercentral.com/Forums/Topic1499938-3077-1.aspx
http://www.sommarskog.se/error-handling-I.html
http://www.codemag.com/Article/0305111
Kalman Toth Database & OLAP Architect
SQL Server 2014 Database Design
New Book / Kindle: Beginner Database Design & SQL Programming Using Microsoft SQL Server 2014 -
Question about error-handling in PL/SQL
Hi friends,
I would like to know if there is a way for error handling for insert and update statements in PL/SQL???
Like when for example an insert fails!
thanxx
SchoeibYou should get a book about such fundamentals!
This is not an online course...
begin
insert into emp values(...);
exception
when no_data_found then
when others then
end; -
Iterations in SQL...
Hello:
I am working with Oracle 11g.
I have a situation like this:
-- drop table t;
create table t (id number, cust_id number, pct number, amt number, primary key(id));
insert into t values ( 1,123,27,100);
insert into t values ( 2,123,27,-70);
insert into t values ( 3,123,27,180);
insert into t values ( 4,123,27,-200);
insert into t values ( 5,123,27,20);
insert into t values (10,123,20,-100);
insert into t values (11,123,20,-200);
insert into t values (12,123,20,-50);
insert into t values (13,123,20,10);The table has a primary key (id), a customer identifier (cust_id), a discount percent (pct), and an amount (amt).
The amount may be positive or negative.
When the amount is negative it has to be "balanced" with a positive one, proceeding in order with the primary key, in the group (partition, in analytic terms) of data given by customer code and percent discount.
The first positive amount has to be "balanced" with the first negative amount.
If the result is positive, the remaining will be "balanced" with the second negative amount, proceeding until no more negative amounts, or until the positive value is zeroed.
When the first positive amount is zeroed, I have to proceed with the second positive amount, and "balance" it with the negative amounts not already previously used.
The process ends when I have no more negative amounts to subtract, or when I have zeroed every positive amount.
The "balancing" process should go like this, in the "BALANCED AMOUNT" column i have put the iterations used to compute the values.
ID CUST_ID PCT AMT BALANCED AMOUNT
1 123 27 100 30 0 0
2 123 27 -70 0 0 0
3 123 27 180 180 180 10
4 123 27 -200 -200 -170 0
5 123 27 20 20 20 20
10 123 20 -100 -90
11 123 20 -200 -200
12 123 20 -50 -50
13 123 20 10 0In the slice of data with PCT=27 I subtract amount -70 from 100, then I balance the next negative amount (-200) with the remaining 30, and then I balance the remaining -170 with 180. The last iteration represents the data I want to have.
In the slice with PCT=20 I have only one positive amount (10), balanced with the first negative amount (-100).
The result I want to have is:
ID CUST_ID PCT AMT BALANCED AMOUNT
1 123 27 100 0
2 123 27 -70 0
3 123 27 180 10
4 123 27 -200 0
5 123 27 20 20
10 123 20 -100 -90
11 123 20 -200 -200
12 123 20 -50 -50
13 123 20 10 0I am wondering if it is possible to produce this result with a single sql statement...
Any suggestions welcome.
Thanks,
AndreaI think it is possible. However the "iterative" rules that you want to apply are somewhat complex. If I understood correctly it is the same a doing a kind negative cumulation working on the difference between total positive and total negative amounts.
As a starter...
select t.*,
sum(t.amt) over (partition by cust_id, pct order by id rows between unbounded preceding and unbounded following) total,
sum(greatest(t.amt,0)) over (partition by cust_id, pct order by id rows between unbounded preceding and unbounded following) total_pos,
sum(least(t.amt,0)) over (partition by cust_id, pct order by id rows between unbounded preceding and unbounded following) total_neg,
sign(sum(t.amt) over (partition by cust_id, pct order by id rows between unbounded preceding and unbounded following)) sign_total,
sum(t.amt) over (partition by cust_id, pct order by id desc rows between unbounded preceding and current row) cum_bottom2top,
sum(greatest(t.amt,0)) over (partition by cust_id, pct order by id desc rows between unbounded preceding and current row) cum_bottom2top_pos,
sum(least(t.amt,0)) over (partition by cust_id, pct order by id desc rows between unbounded preceding and current row) cum_bottom2top_neg
from t
order by id;
ID CUST_ID PCT AMT TOTAL TOTAL_POS TOTAL_NEG SIGN_TOTAL CUM_BOTTOM2TOP CUM_BOTTOM2TOP_POS CUM_BOTTOM2TOP_NEG
1 123 27 100 30 300 -270 1 30 300 -270
2 123 27 -70 30 300 -270 1 -70 200 -270
3 123 27 180 30 300 -270 1 0 200 -200
4 123 27 -200 30 300 -270 1 -180 20 -200
5 123 27 20 30 300 -270 1 20 20 0
10 123 20 -100 -340 10 -350 -1 -340 10 -350
11 123 20 -200 -340 10 -350 -1 -240 10 -250
12 123 20 -50 -340 10 -350 -1 -40 10 -50
13 123 20 10 -340 10 -350 -1 10 10 0
9 rows selected.
SQL> If the total is positive, we continue only with the positive numbers. If the total is negative we work only with negative numbers.
select t2.*,
case when sign(total) = 1 and sign(amt) = 1 then total-cum_bottom2top_pos else 0 end rest_pos,
nvl(lead(case when sign(total) = 1 and sign(amt) = 1 then total-cum_bottom2top_pos else 0 end,1) over (partition by cust_id, pct, sign(total), sign(amt) order by id),0) distribute_rest,
greatest(nvl(lead(case when sign(total) = 1 and sign(amt) = 1 then total-cum_bottom2top_pos else 0 end,1) over (partition by cust_id, pct, sign(total), sign(amt) order by id),0),0) balanced_rest,
case when (case when sign(total) = 1 and sign(amt) = 1 then total-cum_bottom2top_pos else 0 end) < 0 -- rest_pos is negative
then greatest(nvl(lead(case when sign(total) = 1 and sign(amt) = 1 then total-cum_bottom2top_pos else 0 end,1) over (partition by cust_id, pct, sign(total), sign(amt) order by id),0),0) -- use balanced_rest
when (case when sign(total) = 1 and sign(amt) = 1 then total-cum_bottom2top_pos else 0 end) > 0 -- rest_pos is positve
then amt -- use amt
else
0
end balanced_amount
from (select t.id, t.cust_id, t.pct, t.amt,
sum(t.amt) over (partition by cust_id, pct order by id rows between unbounded preceding and unbounded following) total,
sum(t.amt) over (partition by cust_id, pct order by id desc rows between unbounded preceding and current row) cum_bottom2top,
sum(greatest(t.amt,0)) over (partition by cust_id, pct order by id desc rows between unbounded preceding and current row) cum_bottom2top_pos
from t
) t2
order by id;
ID CUST_ID PCT AMT TOTAL CUM_BOTTOM2TOP CUM_BOTTOM2TOP_POS REST_POS DISTRIBUTE_REST BALANCED_REST BALANCED_AMOUNT
1 123 27 100 30 30 300 -270 -170 0 0
2 123 27 -70 30 -70 200 0 0 0 0
3 123 27 180 30 0 200 -170 10 10 10
4 123 27 -200 30 -180 20 0 0 0 0
5 123 27 20 30 20 20 10 0 0 20
10 123 20 -100 -340 -340 10 0 0 0 0
11 123 20 -200 -340 -240 10 0 0 0 0
12 123 20 -50 -340 -40 10 0 0 0 0
13 123 20 10 -340 10 10 0 0 0 0
9 rows selected.
SQL> supplied only the solution for positive amounts. Let you work out the negative version.
I think there is also much room for optimizing the statements, but at least it seems working.
Edited by: Sven W. on Jul 24, 2009 4:38 PM -- removed some columns -
Error handling in Native SQL for ORACLE
Hi,
I have the next code:
DATA instr TYPE char4.
EXEC SQL.
SELECT INSTRUMENTO INTO instr FROM DATOSMAESTROS
END EXEC.
And I want to control if the select has no results. Is it possible with the statement EXCEPTION inside EXEC SQL? Something like that:
DATA instr TYPE char4.
EXEC SQL.
SELECT INSTRUMENTO INTO instr FROM DATOSMAESTROS WHERE id_inst = '01'
EXCEPTION
WHEN NO_DATA_FOUND THEN
:err = SQLCODE
INSERT INTO error( field, code_err) VALUES ( 'instrumento',:err)
END EXEC.
Is this a correct code? If not, how can I do it?
Thank you all,
Cris.Hello,
Take a look on this: http://help.sap.com/saphelp_nw04s/helpdata/en/fc/eb3b8b358411d1829f0000e829fbfe/frameset.htm
Try this:
DATA instr TYPE char4.
EXEC SQL.
SELECT INSTRUMENTO INTO :instr FROM DATOSMAESTROS
ENDEXEC.
Look that I put : inside the native SQL before the intr.
To catch if no data was recovered try this:
DATA instr TYPE char4.
EXEC SQL PERFORMING no_data.
SELECT INSTRUMENTO INTO :instr FROM DATOSMAESTROS
ENDEXEC.
FORM no_data.
IF instr IS INITIAL.
MESSAGE ...
ENDIF.
ENDFORM.
Regards. -
How ot handle ' in PL/SQL package
Hi All !
How can I handle the sign ' in the phrase OU=Admin ID's in this package ?
DECLARE
-- Adjust as necessary.
l_ldap_host VARCHAR2 (256) := 'SERVERNAME';
l_ldap_port VARCHAR2 (256) := '389';
l_ldap_user VARCHAR2 (256) := 'CN=username,OU=Admin ID's,OU=XXXXX,DC=XX,DC=XXX,DC=com';
l_ldap_passwd VARCHAR2 (256) := 'XXXXX';
l_ldap_base VARCHAR2 (256) := 'DC=XX,DC=XXX,DC=COM';
l_retval PLS_INTEGER;
l_session DBMS_LDAP.SESSION;
l_attrs DBMS_LDAP.string_collection;
l_message DBMS_LDAP.MESSAGE;
l_entry DBMS_LDAP.MESSAGE;
l_attr_name VARCHAR2 (256);
l_ber_element DBMS_LDAP.ber_element;
l_vals DBMS_LDAP.string_collection;
BEGIN
Get always error....Thanks'CN=username,OU=Admin ID's,OU=XXXXX,DC=XX,DC=XXX,DC=com';'CN=username,OU=Admin ID''s,OU=XXXXX,DC=XX,DC=XXX,DC=com';
-
Handling EXCEPTION in SQL query itself
Hi friends,
I have situation like the following:
SELECT CASE WHEN ('1') > 0 THEN 'Y'
ELSE 'N'
END
FROM dual;
For this query, Oracle returns 'Y'. That's OK. Somtimes instead of '1' some string may come ('1a' or 'gf'). In such cases Oracle returns 'invalid number' exception. As per my requirement, in such cases, 'N' should be returned.
Is it possible to perform this in SQL (without going to PLSQL)?
Thanks in advance."case-when" statements are evaluated in order.
so you must do something like this:
SELECT
CASE WHEN <is not number>THEN 'N'
CASE WHEN <is greater than 0>THEN 'Y'
Now "<is greater than 0>" will always have number for input, can't get "not number" error there.
See this thread:
Re: regular expression: integer is between N..M
Edited by: CharlesRoos on May 27, 2010 5:03 AM -
File Handling - Iterating through a whole directory
How can you cycle through all the files in a given directory, and then select the ones you think you need? What I need to do is cycle through all the files in a directory and pick out the text files with a specific name. Is this done with FilenameFilter?
TIA.You can use File.list[b] or File.listFiles[b] with, or without a FilenameFiler.
-
PL/SQL 101 : Exception Handling
Frequently I see questions and issues around the use of Exception/Error Handling in PL/SQL. More often than not the issue comes from the questioners misunderstanding about how PL/SQL is constructed and executed, so I thought I'd write a small article covering the key concepts to give a clear picture of how it all hangs together. (Note: the examples are just showing examples of the exception handling structure, and should not be taken as truly valid code for ways of handling things)
Exception Handling
Contents
1. Understanding Execution Blocks (part 1)
2. Execution of the Execution Block
3. Exceptions
4. Understanding Execution Blocks (part 2)
5. How to continue exection of statements after an exception
6. User defined exceptions
7. Line number of exception
8. Exceptions within code within the exception block
1. Understanding Execution Blocks (part 1)
The first thing that one needs to understand is almost taking us back to the basics of PL/SQL... how a PL/SQL execution block is constructed.
Essentially an execution block is made of 3 sections...
+---------------------------+
| Declaration Section |
+---------------------------+
| Statements Section |
+---------------------------+
| Exception Section |
+---------------------------+
The Declaration section is the part defined between the PROCEDURE/FUNCTION header or the DECLARE keyword (for anonymous blocks) and the BEGIN keyword. (Optional section)
The Statements section is where your code goes and lies between the BEGIN keyword and the EXCEPTION keyword (or END keyword if there is no EXCEPTION section). (Mandatory section)
The Exception section is where any exception handling goes and lies between the EXCEPTION keyword at the END keyword. (Optional section)
Example of an anonymous block...
DECLARE
.. declarative statements go here ..
BEGIN
.. code statements go here ..
EXCEPTION
.. exception handlers go here ..
END;
Example of a procedure/function block...
[CREATE OR REPLACE] (PROCEDURE|FUNCTION) <proc or fn name> [(<parameters>)] [RETURN <datatype>] (IS|AS)
.. declarative statements go here ..
BEGIN
.. code statements go here ..
EXCEPTION
.. exception handlers go here ..
END;
(Note: The same can also be done for packages, but let's keep it simple)
2. Execution of the Execution Block
This may seem a simple concept, but it's surprising how many people have issues showing they haven't grasped it. When an Execution block is entered, the declaration section is processed, creating a scope of variables, types , cursors, etc. to be visible to the execution block and then execution enters into the Statements section. Each statment in the statements section is executed in turn and when the execution completes the last statment the execution block is exited back to whatever called it.
3. Exceptions
Exceptions generally happen during the execution of statements in the Statements section. When an exception happens the execution of statements jumps immediately into the exception section. In this section we can specify what exceptions we wish to 'capture' or 'trap' and do one of the two following things...
(Note: The exception section still has access to all the declared items in the declaration section)
3.i) Handle the exception
We do this when we recognise what the exception is (most likely it's something we expect to happen) and we have a means of dealing with it so that our application can continue on.
Example...
(without the exception handler the exception is passed back to the calling code, in this case SQL*Plus)
SQL> ed
Wrote file afiedt.buf
1 declare
2 v_name VARCHAR2(20);
3 begin
4 select ename
5 into v_name
6 from emp
7 where empno = &empno;
8 dbms_output.put_line(v_name);
9* end;
SQL> /
Enter value for empno: 123
old 7: where empno = &empno;
new 7: where empno = 123;
declare
ERROR at line 1:
ORA-01403: no data found
ORA-06512: at line 4
(with an exception handler, we capture the exception, handle it how we want to, and the calling code is happy that there is no error for it to report)
SQL> ed
Wrote file afiedt.buf
1 declare
2 v_name VARCHAR2(20);
3 begin
4 select ename
5 into v_name
6 from emp
7 where empno = &empno;
8 dbms_output.put_line(v_name);
9 exception
10 when no_data_found then
11 dbms_output.put_line('There is no employee with this employee number.');
12* end;
SQL> /
Enter value for empno: 123
old 7: where empno = &empno;
new 7: where empno = 123;
There is no employee with this employee number.
PL/SQL procedure successfully completed.
3.ii) Raise the exception
We do this when:-
a) we recognise the exception, handle it but still want to let the calling code know that it happened
b) we recognise the exception, wish to log it happened and then let the calling code deal with it
c) we don't recognise the exception and we want the calling code to deal with it
Example of b)
SQL> ed
Wrote file afiedt.buf
1 declare
2 v_name VARCHAR2(20);
3 v_empno NUMBER := &empno;
4 begin
5 select ename
6 into v_name
7 from emp
8 where empno = v_empno;
9 dbms_output.put_line(v_name);
10 EXCEPTION
11 WHEN no_data_found THEN
12 INSERT INTO sql_errors (txt)
13 VALUES ('Search for '||v_empno||' failed.');
14 COMMIT;
15 RAISE;
16* end;
SQL> /
Enter value for empno: 123
old 3: v_empno NUMBER := &empno;
new 3: v_empno NUMBER := 123;
declare
ERROR at line 1:
ORA-01403: no data found
ORA-06512: at line 15
SQL> select * from sql_errors;
TXT
Search for 123 failed.
SQL>
Example of c)
SQL> ed
Wrote file afiedt.buf
1 declare
2 v_name VARCHAR2(20);
3 v_empno NUMBER := &empno;
4 begin
5 select ename
6 into v_name
7 from emp
8 where empno = v_empno;
9 dbms_output.put_line(v_name);
10 EXCEPTION
11 WHEN no_data_found THEN
12 INSERT INTO sql_errors (txt)
13 VALUES ('Search for '||v_empno||' failed.');
14 COMMIT;
15 RAISE;
16 WHEN others THEN
17 RAISE;
18* end;
SQL> /
Enter value for empno: 'ABC'
old 3: v_empno NUMBER := &empno;
new 3: v_empno NUMBER := 'ABC';
declare
ERROR at line 1:
ORA-06502: PL/SQL: numeric or value error: character to number conversion error
ORA-06512: at line 3
SQL> select * from sql_errors;
TXT
Search for 123 failed.
SQL>
As you can see from the sql_errors log table, no log was written so the WHEN others exception was the exception that raised the error to the calling code (SQL*Plus)
4. Understanding Execution Blocks (part 2)
Ok, so now we understand the very basics of an execution block and what happens when an exception happens. Let's take it a step further...
Execution blocks are not just a single simple block in most cases. Often, during our statements section we have a need to call some reusable code and we do that by calling a procedure or function. Effectively this nests the procedure or function's code as another execution block within the current statement section so, in terms of execution, we end up with something like...
+---------------------------------+
| Declaration Section |
+---------------------------------+
| Statements Section |
| . |
| +---------------------------+ |
| | Declaration Section | |
| +---------------------------+ |
| | Statements Section | |
| +---------------------------+ |
| | Exception Section | |
| +---------------------------+ |
| . |
+---------------------------------+
| Exception Section |
+---------------------------------+
Example... (Note: log_trace just writes some text to a table for tracing)
SQL> create or replace procedure a as
2 v_dummy NUMBER := log_trace('Procedure A''s Declaration Section');
3 begin
4 v_dummy := log_trace('Procedure A''s Statement Section');
5 v_dummy := 1/0; -- cause an exception
6 exception
7 when others then
8 v_dummy := log_trace('Procedure A''s Exception Section');
9 raise;
10 end;
11 /
Procedure created.
SQL> create or replace procedure b as
2 v_dummy NUMBER := log_trace('Procedure B''s Declaration Section');
3 begin
4 v_dummy := log_trace('Procedure B''s Statement Section');
5 a; -- HERE the execution passes to the declare/statement/exception sections of A
6 exception
7 when others then
8 v_dummy := log_trace('Procedure B''s Exception Section');
9 raise;
10 end;
11 /
Procedure created.
SQL> exec b;
BEGIN b; END;
ERROR at line 1:
ORA-01476: divisor is equal to zero
ORA-06512: at "SCOTT.B", line 9
ORA-06512: at line 1
SQL> select * from code_trace;
TXT
Procedure B's Declaration Section
Procedure B's Statement Section
Procedure A's Declaration Section
Procedure A's Statement Section
Procedure A's Exception Section
Procedure B's Exception Section
6 rows selected.
SQL>
Likewise, execution blocks can be nested deeper and deeper.
5. How to continue exection of statements after an exception
One of the common questions asked is how to return execution to the statement after the one that created the exception and continue on.
Well, firstly, you can only do this for statements you expect to raise an exception, such as when you want to check if there is no data found in a query.
If you consider what's been shown above you could put any statement you expect to cause an exception inside it's own procedure or function with it's own exception section to handle the exception without raising it back to the calling code. However, the nature of procedures and functions is really to provide a means of re-using code, so if it's a statement you only use once it seems a little silly to go creating individual procedures for these.
Instead, you nest execution blocks directly, to give the same result as shown in the diagram at the start of part 4 of this article.
SQL> ed
Wrote file afiedt.buf
1 create or replace procedure b (p_empno IN VARCHAR2) as
2 v_dummy NUMBER := log_trace('Procedure B''s Declaration Section');
3 begin
4 v_dummy := log_trace('Procedure B''s Statement Section');
5 -- Here we start another execution block nested in the first one...
6 declare
7 v_dummy NUMBER := log_trace('Nested Block Declaration Section');
8 begin
9 v_dummy := log_trace('Nested Block Statement Section');
10 select empno
11 into v_dummy
12 from emp
13 where empno = p_empno; -- Note: the parameters and variables from
parent execution block are available to use!
14 exception
15 when no_data_found then
16 -- This is an exception we can handle so we don't raise it
17 v_dummy := log_trace('No employee was found');
18 v_dummy := log_trace('Nested Block Exception Section - Exception Handled');
19 when others then
20 -- Other exceptions we can't handle so we raise them
21 v_dummy := log_trace('Nested Block Exception Section - Exception Raised');
22 raise;
23 end;
24 -- ...Here endeth the nested execution block
25 -- As the nested block handled it's exception we come back to here...
26 v_dummy := log_trace('Procedure B''s Statement Section Continued');
27 exception
28 when others then
29 -- We'll only get to here if an unhandled exception was raised
30 -- either in the nested block or in procedure b's statement section
31 v_dummy := log_trace('Procedure B''s Exception Section');
32 raise;
33* end;
SQL> /
Procedure created.
SQL> exec b(123);
PL/SQL procedure successfully completed.
SQL> select * from code_trace;
TXT
Procedure B's Declaration Section
Procedure B's Statement Section
Nested Block Declaration Section
Nested Block Statement Section
No employee was found
Nested Block Exception Section - Exception Handled
Procedure B's Statement Section Continued
7 rows selected.
SQL> truncate table code_trace;
Table truncated.
SQL> exec b('ABC');
BEGIN b('ABC'); END;
ERROR at line 1:
ORA-01722: invalid number
ORA-06512: at "SCOTT.B", line 32
ORA-06512: at line 1
SQL> select * from code_trace;
TXT
Procedure B's Declaration Section
Procedure B's Statement Section
Nested Block Declaration Section
Nested Block Statement Section
Nested Block Exception Section - Exception Raised
Procedure B's Exception Section
6 rows selected.
SQL>
You can see from this that, very simply, the code that we expected may have an exception was able to either handle the exception and return to the outer execution block to continue execution, or if an unexpected exception occurred then it was able to be raised up to the outer exception section.
6. User defined exceptions
There are three sorts of 'User Defined' exceptions. There are logical situations (e.g. business logic) where, for example, certain criteria are not met to complete a task, and there are existing Oracle errors that you wish to give a name to in order to capture them in the exception section. The third is raising your own exception messages with our own exception numbers. Let's look at the first one...
Let's say I have tables which detail stock availablility and reorder levels...
SQL> select * from reorder_level;
ITEM_ID STOCK_LEVEL
1 20
2 20
3 10
4 2
5 2
SQL> select * from stock;
ITEM_ID ITEM_DESC STOCK_LEVEL
1 Pencils 10
2 Pens 2
3 Notepads 25
4 Stapler 5
5 Hole Punch 3
SQL>
Now, our Business has told the administrative clerk to check stock levels and re-order anything that is below the re-order level, but not to hold stock of more than 4 times the re-order level for any particular item. As an IT department we've been asked to put together an application that will automatically produce the re-order documents upon the clerks request and, because our company is so tight-ar*ed about money, they don't want to waste any paper with incorrect printouts so we have to ensure the clerk can't order things they shouldn't.
SQL> ed
Wrote file afiedt.buf
1 create or replace procedure re_order(p_item_id NUMBER, p_quantity NUMBER) is
2 cursor cur_stock_reorder is
3 select s.stock_level
4 ,r.stock_level as reorder_level
5 ,(r.stock_level*4) as reorder_limit
6 from stock s join reorder_level r on (s.item_id = r.item_id)
7 where s.item_id = p_item_id;
8 --
9 v_stock cur_stock_reorder%ROWTYPE;
10 begin
11 OPEN cur_stock_reorder;
12 FETCH cur_stock_reorder INTO v_stock;
13 IF cur_stock_reorder%NOTFOUND THEN
14 RAISE no_data_found;
15 END IF;
16 CLOSE cur_stock_reorder;
17 --
18 IF v_stock.stock_level >= v_stock.reorder_level THEN
19 -- Stock is not low enough to warrant an order
20 DBMS_OUTPUT.PUT_LINE('Stock has not reached re-order level yet!');
21 ELSE
22 IF v_stock.stock_level + p_quantity > v_stock.reorder_limit THEN
23 -- Required amount is over-ordering
24 DBMS_OUTPUT.PUT_LINE('Quantity specified is too much. Max for this item: '
||to_char(v_stock.reorder_limit-v_stock.stock_level));
25 ELSE
26 DBMS_OUTPUT.PUT_LINE('Order OK. Printing Order...');
27 -- Here goes our code to print the order
28 END IF;
29 END IF;
30 --
31 exception
32 WHEN no_data_found THEN
33 CLOSE cur_stock_reorder;
34 DBMS_OUTPUT.PUT_LINE('Invalid Item ID.');
35* end;
SQL> /
Procedure created.
SQL> exec re_order(10,100);
Invalid Item ID.
PL/SQL procedure successfully completed.
SQL> exec re_order(3,40);
Stock has not reached re-order level yet!
PL/SQL procedure successfully completed.
SQL> exec re_order(1,100);
Quantity specified is too much. Max for this item: 70
PL/SQL procedure successfully completed.
SQL> exec re_order(2,50);
Order OK. Printing Order...
PL/SQL procedure successfully completed.
SQL>
Ok, so that code works, but it's a bit messy with all those nested IF statements. Is there a cleaner way perhaps? Wouldn't it be nice if we could set up our own exceptions...
SQL> ed
Wrote file afiedt.buf
1 create or replace procedure re_order(p_item_id NUMBER, p_quantity NUMBER) is
2 cursor cur_stock_reorder is
3 select s.stock_level
4 ,r.stock_level as reorder_level
5 ,(r.stock_level*4) as reorder_limit
6 from stock s join reorder_level r on (s.item_id = r.item_id)
7 where s.item_id = p_item_id;
8 --
9 v_stock cur_stock_reorder%ROWTYPE;
10 --
11 -- Let's declare our own exceptions for business logic...
12 exc_not_warranted EXCEPTION;
13 exc_too_much EXCEPTION;
14 begin
15 OPEN cur_stock_reorder;
16 FETCH cur_stock_reorder INTO v_stock;
17 IF cur_stock_reorder%NOTFOUND THEN
18 RAISE no_data_found;
19 END IF;
20 CLOSE cur_stock_reorder;
21 --
22 IF v_stock.stock_level >= v_stock.reorder_level THEN
23 -- Stock is not low enough to warrant an order
24 RAISE exc_not_warranted;
25 END IF;
26 --
27 IF v_stock.stock_level + p_quantity > v_stock.reorder_limit THEN
28 -- Required amount is over-ordering
29 RAISE exc_too_much;
30 END IF;
31 --
32 DBMS_OUTPUT.PUT_LINE('Order OK. Printing Order...');
33 -- Here goes our code to print the order
34 --
35 exception
36 WHEN no_data_found THEN
37 CLOSE cur_stock_reorder;
38 DBMS_OUTPUT.PUT_LINE('Invalid Item ID.');
39 WHEN exc_not_warranted THEN
40 DBMS_OUTPUT.PUT_LINE('Stock has not reached re-order level yet!');
41 WHEN exc_too_much THEN
42 DBMS_OUTPUT.PUT_LINE('Quantity specified is too much. Max for this item: '
||to_char(v_stock.reorder_limit-v_stock.stock_level));
43* end;
SQL> /
Procedure created.
SQL> exec re_order(10,100);
Invalid Item ID.
PL/SQL procedure successfully completed.
SQL> exec re_order(3,40);
Stock has not reached re-order level yet!
PL/SQL procedure successfully completed.
SQL> exec re_order(1,100);
Quantity specified is too much. Max for this item: 70
PL/SQL procedure successfully completed.
SQL> exec re_order(2,50);
Order OK. Printing Order...
PL/SQL procedure successfully completed.
SQL>
That's better. And now we don't have to use all those nested IF statements and worry about it accidently getting to code that will print the order out as, once one of our user defined exceptions is raised, execution goes from the Statements section into the Exception section and all handling of errors is done in one place.
Now for the second sort of user defined exception...
A new requirement has come in from the Finance department who want to have details shown on the order that show a re-order 'indicator' based on the formula ((maximum allowed stock - current stock)/re-order quantity), so this needs calculating and passing to the report...
SQL> ed
Wrote file afiedt.buf
1 create or replace procedure re_order(p_item_id NUMBER, p_quantity NUMBER) is
2 cursor cur_stock_reorder is
3 select s.stock_level
4 ,r.stock_level as reorder_level
5 ,(r.stock_level*4) as reorder_limit
6 ,(((r.stock_level*4)-s.stock_level)/p_quantity) as finance_factor
7 from stock s join reorder_level r on (s.item_id = r.item_id)
8 where s.item_id = p_item_id;
9 --
10 v_stock cur_stock_reorder%ROWTYPE;
11 --
12 -- Let's declare our own exceptions for business logic...
13 exc_not_warranted EXCEPTION;
14 exc_too_much EXCEPTION;
15 begin
16 OPEN cur_stock_reorder;
17 FETCH cur_stock_reorder INTO v_stock;
18 IF cur_stock_reorder%NOTFOUND THEN
19 RAISE no_data_found;
20 END IF;
21 CLOSE cur_stock_reorder;
22 --
23 IF v_stock.stock_level >= v_stock.reorder_level THEN
24 -- Stock is not low enough to warrant an order
25 RAISE exc_not_warranted;
26 END IF;
27 --
28 IF v_stock.stock_level + p_quantity > v_stock.reorder_limit THEN
29 -- Required amount is over-ordering
30 RAISE exc_too_much;
31 END IF;
32 --
33 DBMS_OUTPUT.PUT_LINE('Order OK. Printing Order...');
34 -- Here goes our code to print the order, passing the finance_factor
35 --
36 exception
37 WHEN no_data_found THEN
38 CLOSE cur_stock_reorder;
39 DBMS_OUTPUT.PUT_LINE('Invalid Item ID.');
40 WHEN exc_not_warranted THEN
41 DBMS_OUTPUT.PUT_LINE('Stock has not reached re-order level yet!');
42 WHEN exc_too_much THEN
43 DBMS_OUTPUT.PUT_LINE('Quantity specified is too much. Max for this item: '
||to_char(v_stock.reorder_limit-v_stock.stock_level));
44* end;
SQL> /
Procedure created.
SQL> exec re_order(2,40);
Order OK. Printing Order...
PL/SQL procedure successfully completed.
SQL> exec re_order(2,0);
BEGIN re_order(2,0); END;
ERROR at line 1:
ORA-01476: divisor is equal to zero
ORA-06512: at "SCOTT.RE_ORDER", line 17
ORA-06512: at line 1
SQL>
Hmm, there's a problem if the person specifies a re-order quantity of zero. It raises an unhandled exception.
Well, we could put a condition/check into our code to make sure the parameter is not zero, but again we would be wrapping our code in an IF statement and not dealing with the exception in the exception handler.
We could do as we did before and just include a simple IF statement to check the value and raise our own user defined exception but, in this instance the error is standard Oracle error (ORA-01476) so we should be able to capture it inside the exception handler anyway... however...
EXCEPTION
WHEN ORA-01476 THEN
... is not valid. What we need is to give this Oracle error a name.
This is done by declaring a user defined exception as we did before and then associating that name with the error number using the PRAGMA EXCEPTION_INIT statement in the declaration section.
SQL> ed
Wrote file afiedt.buf
1 create or replace procedure re_order(p_item_id NUMBER, p_quantity NUMBER) is
2 cursor cur_stock_reorder is
3 select s.stock_level
4 ,r.stock_level as reorder_level
5 ,(r.stock_level*4) as reorder_limit
6 ,(((r.stock_level*4)-s.stock_level)/p_quantity) as finance_factor
7 from stock s join reorder_level r on (s.item_id = r.item_id)
8 where s.item_id = p_item_id;
9 --
10 v_stock cur_stock_reorder%ROWTYPE;
11 --
12 -- Let's declare our own exceptions for business logic...
13 exc_not_warranted EXCEPTION;
14 exc_too_much EXCEPTION;
15 --
16 exc_zero_quantity EXCEPTION;
17 PRAGMA EXCEPTION_INIT(exc_zero_quantity, -1476);
18 begin
19 OPEN cur_stock_reorder;
20 FETCH cur_stock_reorder INTO v_stock;
21 IF cur_stock_reorder%NOTFOUND THEN
22 RAISE no_data_found;
23 END IF;
24 CLOSE cur_stock_reorder;
25 --
26 IF v_stock.stock_level >= v_stock.reorder_level THEN
27 -- Stock is not low enough to warrant an order
28 RAISE exc_not_warranted;
29 END IF;
30 --
31 IF v_stock.stock_level + p_quantity > v_stock.reorder_limit THEN
32 -- Required amount is over-ordering
33 RAISE exc_too_much;
34 END IF;
35 --
36 DBMS_OUTPUT.PUT_LINE('Order OK. Printing Order...');
37 -- Here goes our code to print the order, passing the finance_factor
38 --
39 exception
40 WHEN exc_zero_quantity THEN
41 DBMS_OUTPUT.PUT_LINE('Quantity of 0 (zero) is invalid.');
42 WHEN no_data_found THEN
43 CLOSE cur_stock_reorder;
44 DBMS_OUTPUT.PUT_LINE('Invalid Item ID.');
45 WHEN exc_not_warranted THEN
46 DBMS_OUTPUT.PUT_LINE('Stock has not reached re-order level yet!');
47 WHEN exc_too_much THEN
48 DBMS_OUTPUT.PUT_LINE('Quantity specified is too much. Max for this item: '
||to_char(v_stock.reorder_limit-v_stock.stock_level));
49* end;
SQL> /
Procedure created.
SQL> exec re_order(2,0);
Quantity of 0 (zero) is invalid.
PL/SQL procedure successfully completed.
SQL>
Lastly, let's look at raising our own exceptions with our own exception numbers...
SQL> ed
Wrote file afiedt.buf
1 create or replace procedure re_order(p_item_id NUMBER, p_quantity NUMBER) is
2 cursor cur_stock_reorder is
3 select s.stock_level
4 ,r.stock_level as reorder_level
5 ,(r.stock_level*4) as reorder_limit
6 ,(((r.stock_level*4)-s.stock_level)/p_quantity) as finance_factor
7 from stock s join reorder_level r on (s.item_id = r.item_id)
8 where s.item_id = p_item_id;
9 --
10 v_stock cur_stock_reorder%ROWTYPE;
11 --
12 exc_zero_quantity EXCEPTION;
13 PRAGMA EXCEPTION_INIT(exc_zero_quantity, -1476);
14 begin
15 OPEN cur_stock_reorder;
16 FETCH cur_stock_reorder INTO v_stock;
17 IF cur_stock_reorder%NOTFOUND THEN
18 RAISE no_data_found;
19 END IF;
20 CLOSE cur_stock_reorder;
21 --
22 IF v_stock.stock_level >= v_stock.reorder_level THEN
23 -- Stock is not low enough to warrant an order
24 [b]RAISE_APPLICATION_ERROR(-20000, 'Stock has not reached re-order level yet!');[/b]
25 END IF;
26 --
27 IF v_stock.stock_level + p_quantity > v_stock.reorder_limit THEN
28 -- Required amount is over-ordering
29its nice article, have put up this one the blog
site,Nah, I don't have time to blog, but if one of the other Ace's/Experts wants to copy it to a blog with reference back to here (and all due credit given ;)) then that's fine by me.
I'd go for a book like "Selected articles by OTN members" or something. Does anybody have a list of links of all those mentioned articles?Just these ones I've bookmarked...
Introduction to regular expressions ... by CD
When your query takes too long ... by Rob van Wijk
How to pipeline a function with a dynamic number of columns? by ascheffer
PL/SQL 101 : Exception Handling by BluShadow -
Setup problem - sql server 2014 - "could not find the database engine startup handle" - 0x851a0019
I tried to install ,deleted and re-installed several times and no help at all.
visual studio 2013 with update 2 rc and adk installed in my computer.
error code: 0x851a0019
error messege in setup: could not find the database engine startup handle
edition: Microsoft SQL Server 2014 Enterprise (Evaluation)
logs:
Overall summary:
Final result: Failed: see details below
Exit code (Decimal): -2061893607
Start time: 2014-04-03 13:53:29
End time: 2014-04-03 14:47:48
Requested action: Install
Setup completed with required actions for features.
Troubleshooting information for those features:
Next step for RS: Use the following information to resolve the error, uninstall this feature, and then run the setup process again.
Next step for SQLEngine: Use the following information to resolve the error, uninstall this feature, and then run the setup process again.
Next step for DQ: Use the following information to resolve the error, uninstall this feature, and then run the setup process again.
Next step for FullText: Use the following information to resolve the error, uninstall this feature, and then run the setup process again.
Next step for Replication: Use the following information to resolve the error, uninstall this feature, and then run the setup process again.
Machine Properties:
Machine name: ARIELUBA-PC
Machine processor count: 8
OS version: Windows 8
OS service pack:
OS region: United States
OS language: English (United States)
OS architecture: x64
Process architecture: 64 Bit
OS clustered: No
Product features discovered:
Product Instance Instance ID Feature
Language Edition Version Clustered Configured
SQL Server 2012 SQLEXPRESS MSSQL11.SQLEXPRESS Database Engine Services 1033
Express Edition 11.1.3128.0 No Yes
SQL Server 2012 SQLEXPRESS MSSQL11.SQLEXPRESS SQL Server Replication 1033
Express Edition 11.1.3128.0 No Yes
SQL Server 2012 ADK MSSQL11.ADK Database Engine Services
1033 Express Edition 11.0.2100.60 No Yes
SQL Server 2012 ADK MSSQL11.ADK SQL Server Replication
1033 Express Edition 11.0.2100.60 No Yes
SQL Server 2012 LocalDB
1033 Express Edition 11.1.3412.0 No Yes
Package properties:
Description: Microsoft SQL Server 2014
ProductName: SQL Server 2014
Type: RTM
Version: 12
SPLevel: 0
Installation location: C:\Users\Arie Luba\Downloads\WS2012R2DC\SQLServer2014-x64-ENU\x64\setup\
Installation edition: Evaluation
Product Update Status:
None discovered.
User Input Settings:
ACTION: Install
ADDCURRENTUSERASSQLADMIN: true
AGTSVCACCOUNT: NT Service\SQLSERVERAGENT
AGTSVCPASSWORD: *****
AGTSVCSTARTUPTYPE: Manual
ASBACKUPDIR: C:\Program Files\Microsoft SQL Server\MSAS12.MSSQLSERVER\OLAP\Backup
ASCOLLATION: Hebrew_CI_AS
ASCONFIGDIR: C:\Program Files\Microsoft SQL Server\MSAS12.MSSQLSERVER\OLAP\Config
ASDATADIR: C:\Program Files\Microsoft SQL Server\MSAS12.MSSQLSERVER\OLAP\Data
ASLOGDIR: C:\Program Files\Microsoft SQL Server\MSAS12.MSSQLSERVER\OLAP\Log
ASPROVIDERMSOLAP: 1
ASSERVERMODE: MULTIDIMENSIONAL
ASSVCACCOUNT: NT Service\MSSQLServerOLAPService
ASSVCPASSWORD: <empty>
ASSVCSTARTUPTYPE: Automatic
ASSYSADMINACCOUNTS: ARIELUBA-PC\Arie Luba
ASTEMPDIR: C:\Program Files\Microsoft SQL Server\MSAS12.MSSQLSERVER\OLAP\Temp
BROWSERSVCSTARTUPTYPE: Automatic
CLTCTLRNAME:
CLTRESULTDIR: C:\Program Files (x86)\Microsoft SQL Server\DReplayClient\ResultDir\
CLTSTARTUPTYPE: Manual
CLTSVCACCOUNT: NT Service\SQL Server Distributed Replay Client
CLTSVCPASSWORD: <empty>
CLTWORKINGDIR: C:\Program Files (x86)\Microsoft SQL Server\DReplayClient\WorkingDir\
COMMFABRICENCRYPTION: 0
COMMFABRICNETWORKLEVEL: 0
COMMFABRICPORT: 0
CONFIGURATIONFILE: C:\Program Files\Microsoft SQL Server\120\Setup Bootstrap\Log\20140403_135327\ConfigurationFile.ini
CTLRSTARTUPTYPE: Manual
CTLRSVCACCOUNT: NT Service\SQL Server Distributed Replay Controller
CTLRSVCPASSWORD: <empty>
CTLRUSERS: ARIELUBA-PC\Arie Luba
ENABLERANU: false
ENU: true
ERRORREPORTING: false
FEATURES: SQLENGINE, REPLICATION, FULLTEXT, DQ, AS, RS, RS_SHP, RS_SHPWFE, DQC, CONN, IS, BC, SDK, BOL, SSMS, ADV_SSMS, DREPLAY_CTLR, DREPLAY_CLT, MDS
FILESTREAMLEVEL: 0
FILESTREAMSHARENAME: <empty>
FTSVCACCOUNT: NT Service\MSSQLFDLauncher
FTSVCPASSWORD: <empty>
HELP: false
IACCEPTSQLSERVERLICENSETERMS: true
INDICATEPROGRESS: false
INSTALLSHAREDDIR: C:\Program Files\Microsoft SQL Server\
INSTALLSHAREDWOWDIR: C:\Program Files (x86)\Microsoft SQL Server\
INSTALLSQLDATADIR: <empty>
INSTANCEDIR: C:\Program Files\Microsoft SQL Server\
INSTANCEID: MSSQLSERVER
INSTANCENAME: MSSQLSERVER
ISSVCACCOUNT: NT Service\MsDtsServer120
ISSVCPASSWORD: <empty>
ISSVCSTARTUPTYPE: Automatic
MATRIXCMBRICKCOMMPORT: 0
MATRIXCMSERVERNAME: <empty>
MATRIXNAME: <empty>
NPENABLED: 0
PID: *****
QUIET: false
QUIETSIMPLE: false
ROLE: AllFeatures_WithDefaults
RSINSTALLMODE: DefaultNativeMode
RSSHPINSTALLMODE: SharePointFilesOnlyMode
RSSVCACCOUNT: NT Service\ReportServer
RSSVCPASSWORD: <empty>
RSSVCSTARTUPTYPE: Automatic
SAPWD: <empty>
SECURITYMODE: <empty>
SQLBACKUPDIR: <empty>
SQLCOLLATION: Hebrew_CI_AS
SQLSVCACCOUNT: NT Service\MSSQLSERVER
SQLSVCPASSWORD: <empty>
SQLSVCSTARTUPTYPE: Automatic
SQLSYSADMINACCOUNTS: ARIELUBA-PC\Arie Luba
SQLTEMPDBDIR: <empty>
SQLTEMPDBLOGDIR: <empty>
SQLUSERDBDIR: <empty>
SQLUSERDBLOGDIR: <empty>
SQMREPORTING: false
TCPENABLED: 1
UIMODE: Normal
UpdateEnabled: true
UpdateSource: MU
USEMICROSOFTUPDATE: false
X86: false
Configuration file: C:\Program Files\Microsoft SQL Server\120\Setup Bootstrap\Log\20140403_135327\ConfigurationFile.ini
Detailed results:
Feature: Management Tools - Complete
Status: Passed
Feature: Client Tools Connectivity
Status: Passed
Feature: Client Tools SDK
Status: Passed
Feature: Client Tools Backwards Compatibility
Status: Passed
Feature: Management Tools - Basic
Status: Passed
Feature: Reporting Services - Native
Status: Failed: see logs for details
Reason for failure: An error occurred for a dependency of the feature causing the setup process for the feature to fail.
Next Step: Use the following information to resolve the error, uninstall this feature, and then run the setup process again.
Component name: SQL Server Database Engine Services Instance Features
Component error code: 0x851A0019
Error description: Could not find the Database Engine startup handle.
Error help link: http://go.microsoft.com/fwlink?LinkId=20476&ProdName=Microsoft+SQL+Server&EvtSrc=setup.rll&EvtID=50000&ProdVer=12.0.2000.8&EvtType=0xD15B4EB2%400x4BDAF9BA%401306%4025&EvtType=0xD15B4EB2%400x4BDAF9BA%401306%4025
Feature: Database Engine Services
Status: Failed: see logs for details
Reason for failure: An error occurred during the setup process of the feature.
Next Step: Use the following information to resolve the error, uninstall this feature, and then run the setup process again.
Component name: SQL Server Database Engine Services Instance Features
Component error code: 0x851A0019
Error description: Could not find the Database Engine startup handle.
Error help link: http://go.microsoft.com/fwlink?LinkId=20476&ProdName=Microsoft+SQL+Server&EvtSrc=setup.rll&EvtID=50000&ProdVer=12.0.2000.8&EvtType=0xD15B4EB2%400x4BDAF9BA%401306%4025&EvtType=0xD15B4EB2%400x4BDAF9BA%401306%4025
Feature: Data Quality Services
Status: Failed: see logs for details
Reason for failure: An error occurred for a dependency of the feature causing the setup process for the feature to fail.
Next Step: Use the following information to resolve the error, uninstall this feature, and then run the setup process again.
Component name: SQL Server Database Engine Services Instance Features
Component error code: 0x851A0019
Error description: Could not find the Database Engine startup handle.
Error help link: http://go.microsoft.com/fwlink?LinkId=20476&ProdName=Microsoft+SQL+Server&EvtSrc=setup.rll&EvtID=50000&ProdVer=12.0.2000.8&EvtType=0xD15B4EB2%400x4BDAF9BA%401306%4025&EvtType=0xD15B4EB2%400x4BDAF9BA%401306%4025
Feature: Full-Text and Semantic Extractions for Search
Status: Failed: see logs for details
Reason for failure: An error occurred for a dependency of the feature causing the setup process for the feature to fail.
Next Step: Use the following information to resolve the error, uninstall this feature, and then run the setup process again.
Component name: SQL Server Database Engine Services Instance Features
Component error code: 0x851A0019
Error description: Could not find the Database Engine startup handle.
Error help link: http://go.microsoft.com/fwlink?LinkId=20476&ProdName=Microsoft+SQL+Server&EvtSrc=setup.rll&EvtID=50000&ProdVer=12.0.2000.8&EvtType=0xD15B4EB2%400x4BDAF9BA%401306%4025&EvtType=0xD15B4EB2%400x4BDAF9BA%401306%4025
Feature: SQL Server Replication
Status: Failed: see logs for details
Reason for failure: An error occurred for a dependency of the feature causing the setup process for the feature to fail.
Next Step: Use the following information to resolve the error, uninstall this feature, and then run the setup process again.
Component name: SQL Server Database Engine Services Instance Features
Component error code: 0x851A0019
Error description: Could not find the Database Engine startup handle.
Error help link: http://go.microsoft.com/fwlink?LinkId=20476&ProdName=Microsoft+SQL+Server&EvtSrc=setup.rll&EvtID=50000&ProdVer=12.0.2000.8&EvtType=0xD15B4EB2%400x4BDAF9BA%401306%4025&EvtType=0xD15B4EB2%400x4BDAF9BA%401306%4025
Feature: Master Data Services
Status: Passed
Feature: Distributed Replay Client
Status: Passed
Feature: Distributed Replay Controller
Status: Passed
Feature: Integration Services
Status: Passed
Feature: Data Quality Client
Status: Passed
Feature: Analysis Services
Status: Passed
Feature: Reporting Services - SharePoint
Status: Passed
Feature: Reporting Services Add-in for SharePoint Products
Status: Passed
Feature: SQL Browser
Status: Passed
Feature: Documentation Components
Status: Passed
Feature: SQL Writer
Status: Passed
Feature: Setup Support Files
Status: Passed
Rules with failures:
Global rules:
Scenario specific rules:
Rules report file: C:\Program Files\Microsoft SQL Server\120\Setup Bootstrap\Log\20140403_135327\SystemConfigurationCheck_Report.htm
2014-04-03 14:14:28.01 Server Microsoft SQL Server 2014 - 12.0.2000.8 (X64)
Feb 20 2014 20:04:26
Copyright (c) Microsoft Corporation
Enterprise Evaluation Edition (64-bit) on Windows NT 6.3 <X64> (Build 9600: ) (Hypervisor)
2014-04-03 14:14:28.01 Server UTC adjustment: 3:00
2014-04-03 14:14:28.01 Server (c) Microsoft Corporation.
2014-04-03 14:14:28.01 Server All rights reserved.
2014-04-03 14:14:28.01 Server Server process ID is 7148.
2014-04-03 14:14:28.01 Server System Manufacturer: 'Dell Inc.', System Model: 'Inspiron N5110'.
2014-04-03 14:14:28.01 Server Authentication mode is WINDOWS-ONLY.
2014-04-03 14:14:28.01 Server Logging SQL Server messages in file 'C:\Program Files\Microsoft SQL Server\MSSQL12.MSSQLSERVER\MSSQL\Log\ERRORLOG'.
2014-04-03 14:14:28.01 Server The service account is 'NT Service\MSSQLSERVER'. This is an informational message; no user action is required.
2014-04-03 14:14:28.01 Server Registry startup parameters:
-d C:\Program Files\Microsoft SQL Server\MSSQL12.MSSQLSERVER\MSSQL\DATA\master.mdf
-e C:\Program Files\Microsoft SQL Server\MSSQL12.MSSQLSERVER\MSSQL\Log\ERRORLOG
-l C:\Program Files\Microsoft SQL Server\MSSQL12.MSSQLSERVER\MSSQL\DATA\mastlog.ldf
2014-04-03 14:14:28.01 Server Command Line Startup Parameters:
-s "MSSQLSERVER"
-m "SqlSetup"
-Q
-q "Hebrew_CI_AS"
-T 4022
-T 4010
-T 3659
-T 3610
-T 8015
2014-04-03 14:14:28.28 Server SQL Server detected 1 sockets with 4 cores per socket and 8 logical processors per socket, 8 total logical processors; using 8 logical processors based on SQL Server licensing. This is an informational message;
no user action is required.
2014-04-03 14:14:28.28 Server SQL Server is starting at normal priority base (=7). This is an informational message only. No user action is required.
2014-04-03 14:14:28.28 Server Detected 8099 MB of RAM. This is an informational message; no user action is required.
2014-04-03 14:14:28.28 Server Using conventional memory in the memory manager.
2014-04-03 14:14:28.31 Server Default collation: SQL_Latin1_General_CP1_CI_AS (us_english 1033)
2014-04-03 14:14:28.34 Server Perfmon counters for resource governor pools and groups failed to initialize and are disabled.
2014-04-03 14:14:28.36 Server Query Store settings initialized with enabled = 1,
2014-04-03 14:14:28.36 Server The maximum number of dedicated administrator connections for this instance is '1'
2014-04-03 14:14:28.36 Server Node configuration: node 0: CPU mask: 0x00000000000000ff:0 Active CPU mask: 0x00000000000000ff:0. This message provides a description of the NUMA configuration for this computer. This is an informational message
only. No user action is required.
2014-04-03 14:14:28.38 Server Using dynamic lock allocation. Initial allocation of 2500 Lock blocks and 5000 Lock Owner blocks per node. This is an informational message only. No user action is required.
2014-04-03 14:14:28.39 Server Database Mirroring Transport is disabled in the endpoint configuration.
2014-04-03 14:14:28.39 spid8s Warning ******************
2014-04-03 14:14:28.39 spid8s SQL Server started in single-user mode. This an informational message only. No user action is required.
2014-04-03 14:14:28.40 spid8s Starting up database 'master'.
2014-04-03 14:14:28.42 Server Software Usage Metrics is disabled.
2014-04-03 14:14:28.48 Server CLR version v4.0.30319 loaded.
2014-04-03 14:14:28.56 Server Common language runtime (CLR) functionality initialized using CLR version v4.0.30319 from C:\Windows\Microsoft.NET\Framework64\v4.0.30319\.
2014-04-03 14:14:28.62 spid8s SQL Server Audit is starting the audits. This is an informational message. No user action is required.
2014-04-03 14:14:28.63 spid8s SQL Server Audit has started the audits. This is an informational message. No user action is required.
2014-04-03 14:14:28.64 spid8s SQL Trace ID 1 was started by login "sa".
2014-04-03 14:14:28.64 spid8s Server name is 'ARIELUBA-PC'. This is an informational message only. No user action is required.
2014-04-03 14:14:28.65 spid16s Password policy update was successful.
2014-04-03 14:14:28.66 spid16s Error: 17190, Severity: 16, State: 1.
2014-04-03 14:14:28.66 spid16s Initializing the FallBack certificate failed with error code: 1, state: 20, error number: 0.
2014-04-03 14:14:28.66 spid16s Unable to initialize SSL encryption because a valid certificate could not be found, and it is not possible to create a self-signed certificate.
2014-04-03 14:14:28.66 spid16s Error: 17182, Severity: 16, State: 1.
2014-04-03 14:14:28.66 spid16s TDSSNIClient initialization failed with error 0x80092004, status code 0x80. Reason: Unable to initialize SSL support. Cannot find object or property.
2014-04-03 14:14:28.66 spid16s Error: 17182, Severity: 16, State: 1.
2014-04-03 14:14:28.66 spid16s TDSSNIClient initialization failed with error 0x80092004, status code 0x1. Reason: Initialization failed with an infrastructure error. Check for previous errors. Cannot find object or property.
2014-04-03 14:14:28.66 spid16s Error: 17826, Severity: 18, State: 3.
2014-04-03 14:14:28.66 spid16s Could not start the network library because of an internal error in the network library. To determine the cause, review the errors immediately preceding this one in the error log.
2014-04-03 14:14:28.67 spid16s Error: 17120, Severity: 16, State: 1.
2014-04-03 14:14:28.67 spid16s SQL Server could not spawn FRunCommunicationsManager thread. Check the SQL Server error log and the Windows event logs for information about possible related problems.
________________________________________________________________________________________________Is it okay? (see below)
;SQL Server 2014 Configuration File
[OPTIONS]
; Specifies a Setup work flow, like INSTALL, UNINSTALL, or UPGRADE. This is a required parameter.
ACTION="Install"
; Detailed help for command line argument ROLE has not been defined yet.
ROLE="AllFeatures_WithDefaults"
; Use the /ENU parameter to install the English version of SQL Server on your localized Windows operating system.
ENU="True"
; Parameter that controls the user interface behavior. Valid values are Normal for the full UI,AutoAdvance for a simplied UI, and EnableUIOnServerCore for bypassing Server Core setup GUI block.
UIMODE="Normal"
; Setup will not display any user interface.
QUIET="False"
; Setup will display progress only, without any user interaction.
QUIETSIMPLE="False"
; Specify whether SQL Server Setup should discover and include product updates. The valid values are True and False or 1 and 0. By default SQL Server Setup will include updates that are found.
UpdateEnabled="True"
; Specify if errors can be reported to Microsoft to improve future SQL Server releases. Specify 1 or True to enable and 0 or False to disable this feature.
ERRORREPORTING="False"
; If this parameter is provided, then this computer will use Microsoft Update to check for updates.
USEMICROSOFTUPDATE="False"
; Specifies features to install, uninstall, or upgrade. The list of top-level features include SQL, AS, RS, IS, MDS, and Tools. The SQL feature will install the Database Engine, Replication, Full-Text, and Data Quality Services (DQS) server. The Tools feature
will install Management Tools, Books online components, SQL Server Data Tools, and other shared components.
FEATURES=SQLENGINE,REPLICATION,FULLTEXT,DQ,AS,RS,RS_SHP,RS_SHPWFE,DQC,CONN,IS,BC,SDK,BOL,SSMS,ADV_SSMS,DREPLAY_CTLR,DREPLAY_CLT,MDS
; Specify the location where SQL Server Setup will obtain product updates. The valid values are "MU" to search Microsoft Update, a valid folder path, a relative path such as .\MyUpdates or a UNC share. By default SQL Server Setup will search Microsoft Update
or a Windows Update service through the Window Server Update Services.
UpdateSource="MU"
; Displays the command line parameters usage
HELP="False"
; Specifies that the detailed Setup log should be piped to the console.
INDICATEPROGRESS="False"
; Specifies that Setup should install into WOW64. This command line argument is not supported on an IA64 or a 32-bit system.
X86="False"
; Specify the root installation directory for shared components. This directory remains unchanged after shared components are already installed.
INSTALLSHAREDDIR="C:\Program Files\Microsoft SQL Server"
; Specify the root installation directory for the WOW64 shared components. This directory remains unchanged after WOW64 shared components are already installed.
INSTALLSHAREDWOWDIR="C:\Program Files (x86)\Microsoft SQL Server"
; Specify a default or named instance. MSSQLSERVER is the default instance for non-Express editions and SQLExpress for Express editions. This parameter is required when installing the SQL Server Database Engine (SQL), Analysis Services (AS), or Reporting Services
(RS).
INSTANCENAME="MSSQLSERVER"
; Specify that SQL Server feature usage data can be collected and sent to Microsoft. Specify 1 or True to enable and 0 or False to disable this feature.
SQMREPORTING="False"
; Specify the Instance ID for the SQL Server features you have specified. SQL Server directory structure, registry structure, and service names will incorporate the instance ID of the SQL Server instance.
INSTANCEID="MSSQLSERVER"
; The computer name that the client communicates with for the Distributed Replay Controller service.
CLTCTLRNAME="SQLDRC"
; The Windows account(s) used to grant permission to the Distributed Replay Controller service.
CTLRUSERS="ARIELUBA-PC\Arie Luba"
; The account used by the Distributed Replay Controller service.
CTLRSVCACCOUNT="NT Service\SQL Server Distributed Replay Controller"
; The startup type for the Distributed Replay Controller service.
CTLRSTARTUPTYPE="Manual"
; The account used by the Distributed Replay Client service.
CLTSVCACCOUNT="NT Service\SQL Server Distributed Replay Client"
; The startup type for the Distributed Replay Client service.
CLTSTARTUPTYPE="Manual"
; The result directory for the Distributed Replay Client service.
CLTRESULTDIR="C:\Program Files (x86)\Microsoft SQL Server\DReplayClient\ResultDir"
; The working directory for the Distributed Replay Client service.
CLTWORKINGDIR="C:\Program Files (x86)\Microsoft SQL Server\DReplayClient\WorkingDir"
; RSInputSettings_RSInstallMode_Description
RSINSTALLMODE="DefaultNativeMode"
; RSInputSettings_RSInstallMode_Description
RSSHPINSTALLMODE="SharePointFilesOnlyMode"
; Specify the installation directory.
INSTANCEDIR="C:\Program Files\Microsoft SQL Server"
; Agent account name
AGTSVCACCOUNT="NT Service\SQLSERVERAGENT"
; Auto-start service after installation.
AGTSVCSTARTUPTYPE="Manual"
; Startup type for Integration Services.
ISSVCSTARTUPTYPE="Automatic"
; Account for Integration Services: Domain\User or system account.
ISSVCACCOUNT="NT Service\MsDtsServer120"
; The name of the account that the Analysis Services service runs under.
ASSVCACCOUNT="NT Service\MSSQLServerOLAPService"
; Controls the service startup type setting after the service has been created.
ASSVCSTARTUPTYPE="Automatic"
; The collation to be used by Analysis Services.
ASCOLLATION="Hebrew_CI_AS"
; The location for the Analysis Services data files.
ASDATADIR="C:\Program Files\Microsoft SQL Server\MSAS12.MSSQLSERVER\OLAP\Data"
; The location for the Analysis Services log files.
ASLOGDIR="C:\Program Files\Microsoft SQL Server\MSAS12.MSSQLSERVER\OLAP\Log"
; The location for the Analysis Services backup files.
ASBACKUPDIR="C:\Program Files\Microsoft SQL Server\MSAS12.MSSQLSERVER\OLAP\Backup"
; The location for the Analysis Services temporary files.
ASTEMPDIR="C:\Program Files\Microsoft SQL Server\MSAS12.MSSQLSERVER\OLAP\Temp"
; The location for the Analysis Services configuration files.
ASCONFIGDIR="C:\Program Files\Microsoft SQL Server\MSAS12.MSSQLSERVER\OLAP\Config"
; Specifies whether or not the MSOLAP provider is allowed to run in process.
ASPROVIDERMSOLAP="1"
; Specifies the list of administrator accounts that need to be provisioned.
ASSYSADMINACCOUNTS="ARIELUBA-PC\Arie Luba"
; Specifies the server mode of the Analysis Services instance. Valid values are MULTIDIMENSIONAL and TABULAR. The default value is MULTIDIMENSIONAL.
ASSERVERMODE="MULTIDIMENSIONAL"
; CM brick TCP communication port
COMMFABRICPORT="0"
; How matrix will use private networks
COMMFABRICNETWORKLEVEL="0"
; How inter brick communication will be protected
COMMFABRICENCRYPTION="0"
; TCP port used by the CM brick
MATRIXCMBRICKCOMMPORT="0"
; Startup type for the SQL Server service.
SQLSVCSTARTUPTYPE="Automatic"
; Level to enable FILESTREAM feature at (0, 1, 2 or 3).
FILESTREAMLEVEL="0"
; Set to "1" to enable RANU for SQL Server Express.
ENABLERANU="False"
; Specifies a Windows collation or an SQL collation to use for the Database Engine.
SQLCOLLATION="Hebrew_CI_AS"
; Account for SQL Server service: Domain\User or system account.
SQLSVCACCOUNT="NT Service\MSSQLSERVER"
; Windows account(s) to provision as SQL Server system administrators.
SQLSYSADMINACCOUNTS="ARIELUBA-PC\Arie Luba"
; Provision current user as a Database Engine system administrator for %SQL_PRODUCT_SHORT_NAME% Express.
ADDCURRENTUSERASSQLADMIN="True"
; Specify 0 to disable or 1 to enable the TCP/IP protocol.
TCPENABLED="1"
; Specify 0 to disable or 1 to enable the Named Pipes protocol.
NPENABLED="0"
; Startup type for Browser Service.
BROWSERSVCSTARTUPTYPE="Automatic"
; Specifies which account the report server NT service should execute under. When omitted or when the value is empty string, the default built-in account for the current operating system.
; The username part of RSSVCACCOUNT is a maximum of 20 characters long and
; The domain part of RSSVCACCOUNT is a maximum of 254 characters long.
RSSVCACCOUNT="NT Service\ReportServer"
; Specifies how the startup mode of the report server NT service. When
; Manual - Service startup is manual mode (default).
; Automatic - Service startup is automatic mode.
; Disabled - Service is disabled
RSSVCSTARTUPTYPE="Automatic"
; Add description of input argument FTSVCACCOUNT
FTSVCACCOUNT="NT Service\MSSQLFDLauncher" -
How to handle SQL code for Daylight Savings for MST Time zone
Hi,
1. My time zone is MST. My data showing differently as day light saving started from November. Please help me how to handle these issue.
2. After Mar 09 2014 Daylight saving going to end.( For this how to handle in the SQL codes)
Please answer for the above 2 doubts.
Thanks in advance.
Regards,
LuckyAbdulHi Abdul,
Daylight saving is basically like switching to another timezone. If your normal time zone is Mountain Standard Time (MST), you will switch to Mountain Daylight Time in the summer.
If daylight saving or timezones are a concern. It is best to store your dates in a DATETIMEOFFSET(0) column. This data type includes the offset between your selected timezone (MST or MDT) and UTC. The offset between MST and UTC is -7 hours and the offset
between MDT and UTC is -6 hours.
Be sure to datetimeoffset(0) and not just datetimeoffset. datetimeoffset(0) uses 8 bytes to store it's data (same as datetime), but datetimeoffset uses 10 bytes. This is especially important if you are going to index this column.
Also be sure to use a similar data type in your application or the timezone information will be lost. If it is an .Net application you should use The DateTimeOffset type. Most other programming languages have equivalent types.
Hope this helps. If you have anymore questions please let me know.
For more information see:
http://msdn.microsoft.com/en-us/library/bb630289.aspx
http://msdn.microsoft.com/en-us/library/ms187819.aspx
http://msdn.microsoft.com/en-us/library/system.datetimeoffset%28v=vs.110%29.aspx
Maybe you are looking for
-
ITunes won't install (at all) on my Windows 8.1 64 bit computer
I've tried downloading iTunes for Windows 8.1 64-bit computers and it won't install on my machine. I did everything like I think I was supposed to ... but nothing happens. In addition I've tried connnecting my iPhone 5S to a USB port ... nothing good
-
Finished sequences is wrong timebase, cant copy paste into new sequence
I am coming onto a project finishing it for a first time editor and he cut 23.97 footage in a 29.99 seq, there are many time effects etc. I tried copy/pasting into a new seq but everything ends up in different places. I cant change my seq settings as
-
For a couple days now an icon that is a white envelope with a blackberry symbol in the middle and a white and red exclamation point and been on my home screen. i am not able to open the icon and do no know how to get rid of it! someone please help!
-
I have recently bought an msi gx660 but if in the future i will need to format how i can do???I can boot up winows 7 by a pendrive format and install windows 7 or i must use the recovery mode at the boot???
-
OFFICE_CONTROL Excel embedded
Hi, I am trying to program embedded Excel on the WebDynpro ABAP window. I programmed it as in an example, but the result is that a square with "X" sign occurs and nothing more - in Internet Explorer. In Firefox I install unsigned certificate as an ex