Select with IF ELSE statement
I was wondering if I could have a select statement like this in my cursor:
Cursor1 (contactno integer) is
select * from customer where
customer_id = 100
and
if handphone_number is not null then
handphone_number = contactno
else
housephone_number = contactno
end if;If it is not possible, how should I go about it?
Edited by: JoannaLee on Sep 4, 2008 10:18 PM
this statement itself is incorrect
select * from customer where
customer_id = 100
and
if handphone_number is not null then
handphone_number = contactno
else
housephone_number = contactno
end if;
because if handphone number is not null then you join with handphone_number = contactno else also handphone_number = contactno
in both cases you are joining the same column, so if conditions shouldnt be used here,
select * from customer where
customer_id = 100
and housephone_number = contactno
Similar Messages
-
I am having trouble figuring out what to do with this else statement error.........I can't seem to see where I am going wrong...............can anyone help? I can compile it but I just keep getting this one error I can't fix.....................
Program Name: Transfer
import java.io.*;
import java.awt.*;
import java.awt.event.*;
public class Transfer extends Frame implements ActionListener
DataOutputStream output;
//Construct components
Panel dataFields = new Panel();
Panel firstRow = new Panel();
Panel secondRow = new Panel();
Panel thirdRow = new Panel();
Panel fourthRow = new Panel();
Panel buttonArea = new Panel();
Button submit = new Button("Submit");
Button exit = new Button("Exit");
Label firstNameLabel = new Label("Name:");
TextField firstName = new TextField(15);
Label studentIdLabel = new Label("Student ID:");
TextField studentId = new TextField(15);
Label transferCourseLabel = new Label("Transfer Course Number:");
TextField transferCourse = new TextField (15);
Label localCourseLabel = new Label("Local Course Number:");
TextField localCourses = new TextField (15);
public static void main(String args[])
Transfer window = new Transfer();
window.setTitle("Transfer Course Substitutions");
window.setSize(450, 250);
window.setVisible(true);
public Transfer()
//set backgound and layout managers
setBackground(Color.magenta);
setLayout(new BorderLayout());
dataFields.setLayout(new GridLayout(4,2));
FlowLayout rowSetup = new FlowLayout(FlowLayout.LEFT,4,2);
firstRow.setLayout(rowSetup);
secondRow.setLayout(rowSetup);
thirdRow.setLayout(rowSetup);
fourthRow.setLayout(rowSetup);
buttonArea.setLayout(new FlowLayout());
//Add fields to rows
firstRow.add(firstNameLabel);
secondRow.add(studentIdLabel);
thirdRow.add(transferCourseLabel);
fourthRow.add(localCourseLabel);
//Add rows to panel
dataFields.add(firstRow);
dataFields.add(secondRow);
dataFields.add(thirdRow);
dataFields.add(fourthRow);
//Add buttons to panel
buttonArea.add(submit);
buttonArea.add(exit);
//Add panels to frame
add(dataFields, BorderLayout.NORTH);
add(buttonArea, BorderLayout.SOUTH);
//Add functionality to buttons
submit.addActionListener(this);
exit.addActionListener(this);
// output states
try
output = new DataOuputStream(new FileOUtputStream("Transfer.dat"));
catch(IOException ex)
System.exit(1);
//construct window listener
addWindowListener(
new WindowAdapter()
public void windowClosing(WindowEvent e)
System.exit(0);
public void actionPerformed(ActionEvent e)
String arg = e.getActionCommand();
if (arg == "Submit")
try
output.writeUTF(code);
output.writeUTF(firstName.getText());
output.writeUTF(studentId.getText());
output.writeUTF(transferCourse.getText());
output.writeUTF(localCourse.getText());
catch(IOException ex)
System.exit(1);
clearFields();
else //code to execute if the user clicks Exit
try
output.close();
catch(IOException c)
System.exit(1);
System.exit(0);
public void clearFields()
firstName.setText("");
studentId.setText("");
transferCourse.setText("");
localCourse.setText("");
firstName.requestFocus();The == method does work but it compares Object references and not the String contents. If the string you are comparing is actually the same object it will reply with 'true' also id both Strings are generated with quotes in the same methos and they contain the same string it will also work. This because the compiler will optimize your creating 2 identical Strings to 1 crete statement.
String a = "Hello";
String b = "Hello";
String c = new String("Hello");
String d = "He" + "llo";
String e = "He";
e +="llo";
a == b ==> true : because of optimization
a == c ==> false: because of different objects
a.equals(c) ==> true
a == d ==> true : because of optimization
a == e ==> false : because of different objects -
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. -
Problem with if/else statement for adventure game
Can anyone offer a hint as to why I am getting a null value printed out in the last line. I have comments that indicate what progress or validation step has occurred to move forward. There is something obviously not working with my user input if/else block. It's supposed to the user input, n,s,e, or w and execute the code, nextRoom = current.get*(); * - referring to whatever direction is specified by the user. For instance if the user enters "e", then this code is executed ... nextRoom = current.getEast(); and the players' new room is set to this room: player1.setCurrentRoom(nextRoom).
That is not what is currently happened as validated by the last line System.out.println(player1.getCurrentRoom()); which prints null; This must be something obvious no?
Room r1 = new Room(); //instantiates new room r1
r1.setName("Hallway"); //sets r1's name to Hallway
r1.setDescription("Long and dark. There are exits to the north, east and west");
Room r2 = new Room(); //new room2, etc...
r2.setName("Bathroom");
r2.setDescription("Bathroom stinks. There are no doors other than the entry");
Room r3 = new Room();
r3.setName("Kitchen");
r3.setDescription("This is where the food is cooked");
Room r4 = new Room();
r4.setName("Master Bedroom");
r4.setDescription("Bedroom of the master");
r1.setEast(r2); // sets r2 east of r1
r1.setWest(r3); //sets r3 west of r1
r1.setNorth(r4); //sets r4 north of r1
System.out.print("The room east of r1 is: "); // this is simply a check to verify that it has set the room properly and it does
System.out.println(r1.getEast());
System.out.printf("You are currently in the %s", r1.getName());
System.out.println(); //another validation step
System.out.println("There are exits on the north end of the\n" +
"hallway and midway on both sides\n");
System.out.println("To move you can type the following: \n"+
"(n) to move north\n" +
"(e) to move east\n" +
"(w) to move west\n" +
"(s) to move south\n");
player1.setCurrentRoom(r1);
System.out.print("You are currently in ");
System.out.println(player1.getCurrentRoom()); //this prints out the correct value for current Room, which is the Hallway
Room current = player1.getCurrentRoom();
System.out.println(current); //as a double check this does print out the correct value for current, which is the Hallway
System.out.println("Where would like to go? Your choices are east, west, and north.\n" +
"Enter e, n, or w");
Scanner ns = new Scanner(System.in);
String input = ns.next();
Room nextRoom = null;
if (input == "e") {
nextRoom = current.getEast();
else if (input == "n") {
nextRoom = current.getNorth();
else if (input == "w") {
nextRoom = current.getWest();
else if (input == null) {
System.out.println("Illegal Move");
player1.setCurrentRoom(nextRoom); //somehow this is setting the current room value to null
System.out.println(player1.getCurrentRoom()); //this prints out nullI initially thought of that but my IDE (netbeans) gives me the incompatible data types (expects boolean, gets string) error when I use input = rather than input (==.). I really want to avoid asking the dumb ass java questions (I should have posted the new to java forum) but how do you set this up if Scanner is expecting a String, my input variable is String and the if statement is expecting a boolean instead of a String?
Scanner ns = new Scanner(System.in);
String input = ns.next();
if (input = "e" ) {
nextRoom = current.getEast();
else if (input = "n" ) {
nextRoom = current.getNorth();
else if (input = "w" ) {
nextRoom = current.getWest();
else if (input = null) {
System.out.println("Illegal Move");
player1.setCurrentRoom(nextRoom); //somehow this is setting the current room value to null
System.out.println(player1.getCurrentRoom()); //this prints out null -
Powershell Name Change with If else not working as expected
The script we've written below executes the if statement correctly and changes the name properly though the else condition is not working properly. The example data file we use for input is shown below and it's name is namechanges.csv
Test,User,User1,1111,2222,[email protected]
Test,Smith,User2,2222,3333,[email protected]
Test,Jones,User3,3333,4444,[email protected]
Test,Doe,User4,4444,5555,[email protected]
Test,Example,User5,5555,7777,[email protected]
The script shown below changes the name in Active Directory, home directory, and Exchange to a unique username and new last name (eg. maiden name needs changed to married name)
$ADRoot = [ADSI]''
$ADSearch = New-Object System.DirectoryServices.DirectorySearcher($ADRoot)
add-PSSnapIn -name Microsoft.Exchange.Management.PowerShell.Admin
Import-module ActiveDirectory
Get-Content C:\New_Account\namechanges.csv |
ForEach {
$Fname = ($_ -split ',')[0]
$nLname = ($_ -split ',')[1]
$lname = ($_ -split ',')[2]
$NUM = ($_ -split ',')[3]
$ID = ($_ -split ',')[4]
$requestor = ($_ -split ',')[5]
$Counter = 0
$Emp = Get-aduser -Filter {(employeeID -eq $ID)-and (EmployeeNumber -eq $NUM)}
$SamAccount = (get-aduser -Filter {employeeID -eq $ID }).SamAccountName
$SamAccount
$FNAME = (get-aduser -Filter {employeeID -eq $ID }).GivenName
$FNAME
$LNAME = (get-aduser -Filter {employeeID -eq $ID }).Surname
$LNAME
$UserPrincipalName = (get-aduser -Filter {employeeID -eq $ID }).UserPrincipalName
$UserPrincipalName
Start-Sleep 2
Set-ADUser $SamAccount -surname $nlname -DisplayName $FNAME" "$nlname
Start-Sleep 2
if ($Emp -ne $null)
$Counter = 1
$Counter
Do
$F = $Fname.remove($Counter)
$newusername = $F + $nLname
$ADSearch.Filter = "(&(objectClass=user)(sAMAccountName=$newusername))"
$Result = $ADSearch.FindAll()
$t = $result.Count
if ($t -lt 1)
$FoundUniqueUserName = $True
Else
$Counter = $Counter + 1
$FoundUniqueUserName = $False
While ($FoundUniqueUserName -eq $False)
$newusername
Start-Sleep 2
rename-adobject -identity ((get-aduser $Emp).ObjectGUID) -NewName "$Fname $nLname"
Start-Sleep 2
Rename-Item \\secret.com\share\home\$SamAccount $newusername
Start-Sleep 2
Set-ADUser $SamAccount -surname $nlname -DisplayName $Fname" "$nlname
Start-Sleep 2
$newUPN = $newusername + "@secret.com"
Start-Sleep 2
Set-ADUser $SamAccount -SamAccountName $newusername -UserPrincipalName $newUPN
Start-Sleep 5
$Mailbox = Get-Mailbox -Identity $SamAccount
$SMTPAddress = $Mailbox.PrimarySmtpAddress
$Domain = $SMTPAddress.Domain
Start-Sleep 5
$emailaddress = "$newusername@$Domain"
Start-Sleep 5
Set-Mailbox $SamAccount -EmailAddressPolicyEnabled:$False -PrimarySmtpAddress $emailaddress -Alias $newusername
Start-Sleep 5
Set-Mailbox $emailaddress -EmailAddressPolicyEnabled:$true
Start-Sleep 5
$smtpServer = "mail.secret.com"
$msg = new-object Net.Mail.MailMessage
$smtp = new-object Net.Mail.SmtpClient($smtpServer)
$msg.From = "[email protected]"
$msg.To.Add($requestor)
$msg.subject = "A name change request for $FNAME $LNAME was succesfull"
$msg.body = "A name change request for $FNAME $LNAME was succesfull"
$smtp.Send($msg)
Start-Sleep 8
Else
$smtpServer = "mail.secret.com"
$msg = new-object Net.Mail.MailMessage
$smtp = new-object Net.Mail.SmtpClient($smtpServer)
$msg.From = "[email protected]"
$msg.To.Add($requestor)
$msg.subject = "A Name change request was received but the script failed to make the change."
$msg.body = "A name change request for $FNAME $LNAME was requested with the employee id and number of $ID and $NUM. The request was not succesfull"
$smtp.Send($msg)
Out-File C:\New_Account\name_change_log.txt -InputObject "At $([datetime]::now) there was a name change request for $Fname $lname-$nLname with ID of $ID and number of $NUM." -Append
Start-Sleep 5
#Remove-Item C:\New_Account\namechanges.csv
Else {
"Something went wrong"
Can someone take a look at the code and see where I went wrong with the else statement? Let's say hypothetically Test Smith is a common name and already exists in Active Directory in the same OU we attempt to make the username unique however if that
fails I would like to receive the email and update the name change in some other way.Well the code you presented has two issues that I can see
You have the following
While ($FoundUniqueUserName -eq $False)
$newusername
Start-Sleep 2
rename-adobject -identity ((get-aduser $Emp).ObjectGUID) -NewName "$Fname $nLname"
Start-Sleep 2
Rename-Item \\secret.com\share\home\$SamAccount $newusername
Start-Sleep 2
Set-ADUser $SamAccount -surname $nlname -DisplayName $Fname" "$nlname
Start-Sleep 2
$newUPN = $newusername + "@secret.com"
Start-Sleep 2
Set-ADUser $SamAccount -SamAccountName $newusername -UserPrincipalName $newUPN
Start-Sleep 5
$Mailbox = Get-Mailbox -Identity $SamAccount
$SMTPAddress = $Mailbox.PrimarySmtpAddress
$Domain = $SMTPAddress.Domain
Start-Sleep 5
$emailaddress = "$newusername@$Domain"
Start-Sleep 5
Set-Mailbox $SamAccount -EmailAddressPolicyEnabled:$False -PrimarySmtpAddress $emailaddress -Alias $newusername
Start-Sleep 5
Set-Mailbox $emailaddress -EmailAddressPolicyEnabled:$true
Start-Sleep 5
$smtpServer = "mail.secret.com"
$msg = new-object Net.Mail.MailMessage
$smtp = new-object Net.Mail.SmtpClient($smtpServer)
$msg.From = "[email protected]"
$msg.To.Add($requestor)
$msg.subject = "A name change request for $FNAME $LNAME was succesfull"
$msg.body = "A name change request for $FNAME $LNAME was succesfull"
$smtp.Send($msg)
Start-Sleep 8
Which has no open and closing brackets for the while loop, then at the end of the script you have
#Remove-Item C:\New_Account\namechanges.csv
Else
"Something went wrong"
That else has no opening If statement.....I would fix these issues first, straighten your code out a bit and see if it works then, as the no opening and closing brackets on the While loop and the extra else statement, may be giving you some issues.
If you find that my post has answered your question, please mark it as the answer. If you find my post to be helpful in anyway, please click vote as helpful.
Don't Retire Technet -
Looking for a best query for multiple IF Else statement in a single select
Hi
I want to run multiple IF Else statements in a single select SQL, each statement is one SQL operating on the same table, what is the best way to write this select SQL query ?
If it is PL/SQL, when i get the result from the first IF statement I will skip the remaining execution, and so on... Can any one help me on this.
Thanks in advance !!965818 wrote:
I Apologize, the information i have given might not be enough.
This is my scenario,
I am selecting set of rows from the table for the employee id. After selecting those records,
i need to go through the result list and check the condition 1, if it is met, i will return that employee record.
If that condition 1 is not met, then i need to go through the condition 2. If that is met, i will return that record.
Like wise, i have four conditions.
I am trying to achieve this in a single sql. If i am not clear, please let me know.Not fully clear yet, but the picture is better already. The thing with SQL is that you should stop thinking procedurally. Instead think in data sets.
For example if the task is:
Find all managers that work in sales.
Procedural thinking would work like this:
pseudo code
Loop over all employees that work in sales
for each row
check if it is a manager
if manager
then return record
else
do nothing
end
end loopThinking in datasets will result in a different logic
pseudo code
select all employees
where department = SALES
and job = MANAGERThis advantage here is that all the "Do nothing" loops are not needed. Those are already eliminated by the database.
So what is needed to help you? Give the full picture. What is your task that you try to solve. From a business perspective. -
it is possible to write something approaching an if..then..else statement in SQL with 'generalized' conditions in the if statement.
Attached is the query for the payment register, in which I've written a series of decode statements, one for each possible value of the payment code. The query works OK - however, its specific and as the number of paycodes expand (and they do), the report won't pick up the new paycode until the code is changed. More importantly, the report won't be correct until someone 'discovers' that a paycode is missing, which might take months.
If I were writing the equivalent of this series of decode statements in Focus, it would be something like this:
DEFINE.......
PAYMED/D12.2 = IF PAYMENT_CD LE 18
THEN PAYMENT_AMT
ELSE 0 ;
PAYIND/D12.2 = IF PAYMENT_CD GE 19 AND PAYMENT_CD LE 49
THEN PAYMENT_AMT
ELSE 0 ;
PAYEXP/D12.2 = IF PAYMENT_CD GE 70
THEN PAYMENT_AMT
ELSE 0 ;
PAYREC/D12.2 = IF PAYMENT_CD GE 50 AND PAYMENT_CD LE 69
THEN PAYMENT_AMT
ELSE 0;
END
IN SQL/PLUS:
SELECT ACCOUNT_NAME,
LOCATION_1,
CLMNT_LAST_NAME,
CLAIM_NBR,
DATE_OF_INJURY,
DATE_CHECK_REGISTER,
PAYEE_NAME_1,
PAYMENT_CD,
SERV_OFC,
CPO_CHECK_NBR,
PAYMENT_FORM,
DECODE(PAYMENT_CD, 20, PAYMENT_AMT, 21, PAYMENT_AMT,
22, PAYMENT_AMT, 23, PAYMENT_AMT, 25, PAYMENT_AMT,
26, PAYMENT_AMT, 27, PAYMENT_AMT, 28, PAYMENT_AMT,
29, PAYMENT_AMT, 30, PAYMENT_AMT, 31, PAYMENT_AMT,
32, PAYMENT_AMT, 33, PAYMENT_AMT, 34, PAYMENT_AMT,
35, PAYMENT_AMT, 36, PAYMENT_AMT, 37, PAYMENT_AMT,
39, PAYMENT_AMT, 40, PAYMENT_AMT, 41, PAYMENT_AMT,
42, PAYMENT_AMT, 43, PAYMENT_AMT, 44, PAYMENT_AMT,
45, PAYMENT_AMT, 46, PAYMENT_AMT, 47, PAYMENT_AMT,
48, PAYMENT_AMT, 49, PAYMENT_AMT, NULL) INDEMNITY,
DECODE(PAYMENT_CD, 0, PAYMENT_AMT, 1, PAYMENT_AMT,
2, PAYMENT_AMT, 3, PAYMENT_AMT, 4, PAYMENT_AMT,
5, PAYMENT_AMT, 6, PAYMENT_AMT, 7, PAYMENT_AMT,
8, PAYMENT_AMT, 9, PAYMENT_AMT, 10, PAYMENT_AMT,
11, PAYMENT_AMT, 12, PAYMENT_AMT, 13, PAYMENT_AMT,
14, PAYMENT_AMT, 15, PAYMENT_AMT, 18, PAYMENT_AMT,
17, PAYMENT_AMT, NULL) MEDICAL,
DECODE(PAYMENT_CD, 70, PAYMENT_AMT, 71, PAYMENT_AMT,
72, PAYMENT_AMT, 73, PAYMENT_AMT, 74, PAYMENT_AMT,
75, PAYMENT_AMT, 76, PAYMENT_AMT, 77, PAYMENT_AMT,
78, PAYMENT_AMT, 79, PAYMENT_AMT, 80, PAYMENT_AMT,
81, PAYMENT_AMT, 82, PAYMENT_AMT, 83, PAYMENT_AMT,
84, PAYMENT_AMT, 85, PAYMENT_AMT, 86, PAYMENT_AMT,
87, PAYMENT_AMT, 88, PAYMENT_AMT, 89, PAYMENT_AMT,
90, PAYMENT_AMT, NULL) EXPENSES,
DECODE(PAYMENT_CD, 50, PAYMENT_AMT, 51, PAYMENT_AMT,
52, PAYMENT_AMT, 53, PAYMENT_AMT, 54, PAYMENT_AMT,
55, PAYMENT_AMT, 56, PAYMENT_AMT, 57, PAYMENT_AMT,
58, PAYMENT_AMT, NULL) RECOVERIES,
DECODE(PAYMENT_FORM, 'N', PAYMENT_AMT, NULL) NONCASH,
DATE_FROM_SERVICE,
DATE_THRU_SERVICE
FROM &INPUT_TABLES
WHERE &SECURITYCOND
DATE_OF_PAYMENT BETWEEN :START_DATE AND :END_DATE
ORDER BY LOCATION_1, CPO_CHECK_NBR
As you can see, this is both much easier to write and covers the possibility of expansion of paycodes (expansions always fit in these defined ranges).
My question is, then, is it possible to write something like this in SQL and, if so, could you give me some sample code? (I'm one of those people who learn best from looking at the code as opposed to a set of instructions)Here is one way you could do it.
Create a table that has columns like:
Payment_code varchar2(2),
Effective_Date Date,
Payment_type varchar2(20),
Expiration_Date Date)
Payment type for example could be
I- indemnity
M- medical
R- recovery
E- expenses
Let the table name for example be PAYMENT_CODE.
The select query would look like
SELECT ACCOUNT_NAME,
LOCATION_1,
CLMNT_LAST_NAME,
CLAIM_NBR,
DATE_OF_INJURY,
DATE_CHECK_REGISTER,
PAYEE_NAME_1,
PAYMENT_CD,
SERV_OFC,
CPO_CHECK_NBR,
PAYMENT_FORM,
DECODE(p.payment_type,'E',PAYMENT_AMOUNT,0) expenses,
DECODE(p.payment_type,'I',PAYMENT_AMOUNT,0) indemnity,
DECODE(p.payment_type,'M',PAYMENT_AMOUNT,0) Medical,
DECODE(p.payment_type,'R',PAYMENT_AMOUNT,0) recoveries,
DECODE(PAYMENT_FORM, 'N', PAYMENT_AMT, NULL) NONCASH
FROM &INPUT_TABLES,
PAYMENT_CODE P
WHERE P.PAYMENT_CODE = SOMEINPUT_TABLE.PAYMENT_CODE
and other conditions
The idea is to group all the payment codes into a few groups to reduce the clutter. If there is ever a change to the payment code, you could modify the table and it will be reflected in your select query. -
Boolean error with a If else statement
Hello, i am new to java, and the only other programing language i have used is pascal, and compared to java its ALOT different any ways my problem. I am trying to write a simply little program which random selects a number between 1 and 10, i did that fine got to show that on screen with no probelm . Next i wanted to but in a if else statement, depending which numbers was selected it would show a different message this is where i am getting a probelm, here is the code for the whole thing:
// randomColour
import javax.swing.JOptionPane;
public class randomColour {
public static void main ( String args [])
int value;
value = 1 + ( int ) ( Math.random() * 10 );
if (value = "1" )
System.out.println("Green");
else
System.out.println("Blue");
System.exit( 0 );
} // end mainWhen i try to Compile it comes up with error saying required:boolean why is this? and what can i do to change to fix it?A single = is used to indicate assignment. You are testing for equality which requires ==. Also, "1" is a String. Value is an int. Changeif value = "1" to if value == 1Mark
-
Delete statement that uses a sub-select with the statement in the cursor
Hi all,
How to write write a delete statement that uses a sub-select with the statement in the cursor?
CURSOR excluded_dates IS
SELECT TO_TIMESTAMP(report_parameter_value, in_date_format_mask)
INTO my_current_date_time
FROM report_parameters
WHERE report_parameters.report_parameter_id = in_report_parameter_id
AND report_parameters.report_parameter_group = 'DATE_TIME'
AND report_parameters.report_parameter_name = 'EXCLUDED_DATE';
OPEN excluded_dates;
LOOP
FETCH excluded_dates INTO my_excluded_date;
EXIT WHEN excluded_dates%NOTFOUND;
DELETE FROM edr_rpt_tmp_inclusion_table
WHERE TO_CHAR(date_time, 'mm/dd/yyyy') = TO_CHAR(my_excluded_date, 'mm/dd/yyyy');
END LOOP;
CLOSE excluded_dates;ThanksHi,
In such case I think is better to create a view an perform the delete using it. Example (using HR schema):
Connected to Oracle Database 10g Express Edition Release 10.2.0.1.0
Connected as hr
SQL> create or replace view v_employees as select * from employees where first_name like 'J%';
View created
SQL> select * from v_employees;
EMPLOYEE_ID FIRST_NAME LAST_NAME EMAIL PHONE_NUMBER HIRE_DATE JOB_ID SALARY COMMISSION_PCT MANAGER_ID DEPARTMENT_ID
110 John Chen JCHEN 515.124.4269 28/09/1997 FI_ACCOUNT 8200,00 108 100
112 Jose Manuel Urman JMURMAN 515.124.4469 07/03/1998 FI_ACCOUNT 7800,00 108 100
125 Julia Nayer JNAYER 650.124.1214 16/07/1997 ST_CLERK 3200,00 120 50
127 James Landry JLANDRY 650.124.1334 14/01/1999 ST_CLERK 2400,00 120 50
131 James Marlow JAMRLOW 650.124.7234 16/02/1997 ST_CLERK 2500,00 121 50
133 Jason Mallin JMALLIN 650.127.1934 14/06/1996 ST_CLERK 3300,00 122 50
139 John Seo JSEO 650.121.2019 12/02/1998 ST_CLERK 2700,00 123 50
140 Joshua Patel JPATEL 650.121.1834 06/04/1998 ST_CLERK 2500,00 123 50
145 John Russell JRUSSEL 011.44.1344.429268 01/10/1996 SA_MAN 14000,00 0,40 100 80
156 Janette King JKING 011.44.1345.429268 30/01/1996 SA_REP 10000,00 0,35 146 80
176 Jonathon Taylor JTAYLOR 011.44.1644.429265 24/03/1998 SA_REP 8600,00 0,20 149 80
177 Jack Livingston JLIVINGS 011.44.1644.429264 23/04/1998 SA_REP 8400,00 0,20 149 80
181 Jean Fleaur JFLEAUR 650.507.9877 23/02/1998 SH_CLERK 3100,00 120 50
186 Julia Dellinger JDELLING 650.509.3876 24/06/1998 SH_CLERK 3400,00 121 50
189 Jennifer Dilly JDILLY 650.505.2876 13/08/1997 SH_CLERK 3600,00 122 50
200 Jennifer Whalen JWHALEN 515.123.4444 17/09/1987 AD_ASST 4400,00 101 10
16 rows selected
SQL> delete from v_employees where hire_date >= to_date('01/06/1998', 'dd/mm/yyyy');
2 rows deleted
SQL> regards, -
There is an if statement in this servlet which basically checks for null values, that works grand, however, when I added in an else statement (for the try and catch functions), the servlet let won't run. Is it not possible to embed Try and Catch functions with an else loop?
package client;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;
import business.Client;
import data.ClientDB;
import util.MarshPool;
public class AddClientServlet extends HttpServlet{
private MarshPool connectionPool;
public void init() throws ServletException{
connectionPool = MarshPool.getInstance();
public void destroy() {
connectionPool.destroy();
public void doPost(HttpServletRequest request,
HttpServletResponse response)
throws IOException, ServletException{
Connection connection = connectionPool.getConnection();
String clientName = request.getParameter("clientName");
String address1 = request.getParameter("address1");
String address2 = request.getParameter("address2");
String address3 = request.getParameter("address3");
String postCode = request.getParameter("postCode");
String county = request.getParameter("county");
String country = request.getParameter("country");
String since = request.getParameter("since");
String category = request.getParameter("category");
String units = request.getParameter("units");
String company = request.getParameter("company");
String ae = request.getParameter("ae");
String phoneNo = request.getParameter("phoneNo");
String faxNo = request.getParameter("faxNo");
String mobileNo = request.getParameter("mobileNo");
String emailAddress = request.getParameter("emailAddress");
String comments = request.getParameter("comments");
int clientNo = 0;
int active = 0;
String message = "";
HttpSession session = request.getSession();
Client client = new Client (clientNo, clientName, address1, address2, address3, postCode, county, country, company, units, category, ae, emailAddress, phoneNo, faxNo, mobileNo, comments, since, active);
session.setAttribute("client", client);
if ((clientName.length()==0) || (address1.length()==0) ||(category.length()==0) || (units.length()==0) ||(company.length()==0)||(ae.length()==0) ||(country.length()==0) ||(since.length()==0)){
message = "Please enter values in all the required fields";
session.setAttribute("message", message);
RequestDispatcher dispatcher =
getServletContext().getRequestDispatcher(
"/client/missingfield.jsp");
dispatcher.forward(request, response);
else{
try{
ClientDB.addRecord(connection, client);
message = "Client entered successfully";
session.setAttribute("message", message);
RequestDispatcher dispatcher =
getServletContext().getRequestDispatcher(
"/client/added_client.jsp");
dispatcher.forward(request, response);
catch(SQLException sqle){
message = "EmailServlet SQLException: " + sqle;
session.setAttribute("message", message);
RequestDispatcher dispatcher =
getServletContext().getRequestDispatcher(
"/eurosys/");
dispatcher.forward(request, response);
connectionPool.freeConnection(connection);
}If what you mean is that you used to have:
if ( clientName == null // ... ... B4 checking their length, then yeah, put that back in. You can't check the length on a null Object.
But why would you remove that? I think you should post the code the way it existed B4 you altered it and let's see the diff. -
Compilation error with simple if-else statement
package chapterFive;
* Author: Sarab
* Filename: MainClass.java
* Purpose: Try and get my mind around the concept of the selection
* control structures and repetition statements
class MainClass {
public static void main(String [] args)
// some variables and prompt for input
java.util.Scanner scan = new java.util.Scanner(System.in);
System.out.print("Please enter your name: ");
String input = scan.nextLine();
// some repetition statement, for loop
if (input.equals("Sarab"));
System.out.println("Welcome Sarab!");
else
System.out.println("You are in the else statement");
for(int sentinelValue; sentinelValue<5; sentinelValue++)
System.out.println("The following is the numbers 0-4"
+ " printed on separate lines: " + sentinelValue);
System.out.println("This line will print regardless of whether you"
+ " entered the if or the else portion of the selection"
+ " statement.");
}I am getting the following error:
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
Syntax error on token "else", delete this token
at chapterFive.MainClass.main(MainClass.java:26)What's the matter? This looked straight forward enough to me.if (input.equals("Sarab"));
// is the same as
if (input.equals("Sarab")) {}
// so what you have amounts to this:
if (input.equals("Sarab")) {}
System.out.println("Welcome Sarab!");
else { ... }You've got an if block that does nothing, then a block that always executes, calling println, and then your else. Since you have that block between if and else, the if has ended and it's not legal to use else.
Get rid of the semicolon after if. -
Problem with Selection Criteria with 2 or statements.
I have a report with 2 or statements in the selection criteria:
like "US IT GFS INFOSYS*" or
like "US IT GFS INFOSYS*" or
like "US IT GFS INFOSYS*"
I am just trying to do do a count of records. The details has the record # and am doing a distinct count. If I rearrange this or statement, then I get a different count. The above statement gives me a count of 1136. If I rearrange the statement to:
like "US IT GFS INFOSYS*" or
like "US IT GFS INFOSYS*" or
like "US IT GFS INFOSYS*"
I only get 192 records. I don't understand why? Please help.Cara,
When Crystal evaluates an or statement it will stop evaluating after one of the clauses is true. Since the first or clause is returning data, true, it is not evaluating the other 2 clauses. When you change the order I am assuming that the first clause is returning data though different from the original record selection.
You may want to consider using a command object or stored procedure to generate the filter as SQL should evaluate all the or clauses. -
How to total 2 colums with an -If then else- statement each
Hello,
I have 2 colums A en B who generate data based on an “If then else” statement.
Colum A
<?xdofx:if (OMZET_YTD_VJ )!='' then ((OMZET_YTD_VJ) * (BM_YTD - BM_YTD_VJ)) div 100 else 0 end if?>
Colum B
<?xdofx:if (BM_YTD)!='' then ((BM_YTD) * (OMZET_YTD - OMZET_YTD_VJ)) div 100 else 0 end if?>
Colum C needs to be the sum of both. Who can help me?
Thanks a lot.Can you send me the RTF template and xml file to [email protected]? I can take a look and try to help.
Thanks,
Bipuser -
IF ELSE statement / CMOD Code in BEX Query
Hi
I have a requirement in Inventory flow.
Material stock value at the end of each quarter has to be calculator based on cycle count indicator. I have all the values on my cube.
In the report, Calender year and quarter is on the selection screen.
When user enters 2014 and Q2, Data for April, May and June are displaying on the report. But user want data only for June.
At the end of quarter 2 is June, so he wants only Material stock value at the end of June.
If a material stock level is changed in April and May and not changed in June, not data is available for June in my Cube.
In this case for Quarter 2, if June data is missing, it has to look for May data. Even if MAY data is missing, it will have to look for April.
Even if April data is missing, it will have to look for March data.
The result should be
Plant Q1 Q2 Q3 Q4
XYZ 100 100 100 100
If there is no change to stock level in April, May & June - at the end of Quarter 2, the stock value should be 100 as it was in end of Q1.
If no change was dont to stock level until December, the stock level should be 100.
Is there a way out using IF ELSE statements or through CMOD customer exit.
Regards,
Elango MurgesanHI Elango,
the user input on CALQuarter always would be Single value??or can we expect ranges as well?
if single value,
then we can achieve it by having one more dummy KF.
lets say. user input is Q2.
-> in your dummy KF, restrict the Calquarter/Calmonth to last quarter(i.e Q1)using customer exit and make the logic as you said above(last value based on calmonth).(make this KF hidden, as this is not required to display)
-> and in another KF restricted with Q2.Same logic, last value on Calmonth.((make this KF hidden, as this is not required to display)
and now you have 2 KFs in your report. So in a formula, you can have condition-> if Q2 KF is blank, then Q1KF, else Q2 KF.
Hope you are getting my idea.. Please try this and let us know.
** if Q1 also null, then we can extend customer exit logic to may be last one year, and having last value on based on calendar month, we can still achieve i guess.
Regards,
Sakthi. -
Help with if/else in displaying data - (possibly foreach)
Hello all,
I've been trying to set something up, and I'm having difficulty getting it to work.
Lines 84-111 have become my biggest difficulty. I've got an if/else statement set up so that if one record has an image located on the localhost that image is pulled up. The way I have it now, this works great.
If I swap lines 93-96 with 102-105, and just tweek line 90, I can get it to work if the image is located on an alias and not the localhost.
The problem is that if I have it like it is now, I can't get both to work at the same time. So, I'm trying to get the if/else statement to apply to each record that is being pulled up. It seems like what it is doing now is choosing which part of the if/else statement it needs to use for the first record, and then applies that for all records.
Is there a way to have it coded like it is now for the if/else statement (because I want to be able to add multiple alias' and just check to see if the image is on the localhost or not); but have the image be displayed no matter if the image is located on the localhost or an alias?
The following is what I've got so far:
<?php
$search = $_GET['series'];
$query_begin=" SELECT * FROM movies WHERE movie_name_series = '$search' ";
$search_begin = mysql_query($query_begin) or die(mysql_error());
$row_begin = mysql_fetch_assoc($search_begin);
if($row_begin == 0){
?>
<script type="text/javascript"><!--
setTimeout('Redirect()',0000);
function Redirect()
location.href = 'index.php?content=noresult';
// --></script>
<?php
else
$query_display = "SELECT * from series WHERE series_id = '$search'";
$result_display = mysql_query($query_display);
$row_display = mysql_fetch_array($result_display, MYSQL_ASSOC);
$series_id = $row_diaplay['series_id'];
$series_name = $row_display['series_name'];
?>
<h2>All Movies in our Library categorized in the series <?php echo $series_name ?></h2>
<br />
<div style="float: left; width: auto">
Click on the name of the movie to edit the movie.
</div>
<br />
<hr size="1" noshade="noshade" />
<br />
<?php
$query="SELECT * FROM movies
INNER JOIN family_rating ON movies.movie_star_rating=family_rating.star_id
INNER JOIN alias ON movies.alias=alias.alias_id
INNER JOIN parent_alert ON movies.parent_alert=parent_alert.alert_id
INNER JOIN rating ON movies.movie_rating=rating.rating_id
WHERE movies.movie_name_series='$search'
ORDER BY movies.movie_name ASC";
$result= mysql_query($query)or die (mysql_error());
while($row=mysql_fetch_array($result)){
// Display the data
?>
<table width="200" style="margin: 20px">
<tr align="center">
<td valign="top">
<h1 style="font-size: 12px"><?php echo $row['movie_name']; ?></h1>
</td>
</tr>
<tr align="center">
<td valign="top" style="width: 100%; border-bottom: ridge #FFF; border-left: ridge #FFF; background: url(assets/images/transback.png) repeat; padding: 10px">
<a class="ToolText" onMouseOver="javascript:this.className='ToolTextHover'" onMouseOut="javascript:this.className='ToolText'">
<style media="screen" type="text/css">
#coverart {
display: block;
width: 110px;
height: 150px;
#coverart:hover {
background: url("assets/icons/play_movie.png") no-repeat 0 0;
background-size: 110px;
</style>
<p>
<form action="index.php?content=play_movie" method="post">
<input type="hidden" value="<?php echo $row['movie_id']; ?>" name="movie" />
<input type="hidden" value="<?php echo $row['warning'] ?>" name="warning" />
<?php
if ($row['alias_name']='localhost') {
?>
<input onmouseover='this.src="assets/icons/play_movie.png"'
onmouseout='this.src="movies/coverart/<?php echo $row['art']; ?>"'
type="image" src="movies/coverart/<?php echo $row['art']; ?>"
style="border: none" height="150" width="110" />
<?php
}else{
?>
<input onmouseover='this.src="assets/icons/play_movie.png"'
onmouseout='this.src="http://<?php echo $row['ip_address']; ?>/<?php echo $row['alias_name']; ?>/coverart/<?php echo $row['art']; ?>"'
type="image" src="http://<?php echo $row['ip_address']; ?>/<?php echo $row['alias_name']; ?>/coverart/<?php echo $row['art']; ?>"
style="border: none" height="150" width="110" />
<?php
?>
</form>
</p>
<span><h2 align="center"><?php echo $row['movie_name']; ?></h2>
<?php echo $row['rating_name']; ?>
<h4><?php echo $row['description']; ?></h4>
<?php
if($row['parent_alert']='1') {
?>
<p align"center"><img src="assets/icons/<?php echo $row['alert_file_name']; ?>"></p></span>
<?php
} else {
?>
</a>
<img src="assets/icons/s_<?php echo $row['star_file_name']; ?>" />
</td>
</tr>
</table>
<?
?>
I've looked through a number of tutorials and it's been indicated to use a for each loop. However, I can't seem to get this to work. Is there anything I can do to get this to work the way I am trying to? Is it a problem with my if/else or do I need a for each? If I need a for each, how do I do that?
Thanks.Thank you for your reply. I apologize for not being as clear as I needed to be, so I'll try and explain better.
I've got a page that pulls up some records from a database, where I've got an if / else statement as part of the section where it displays the data.
<?php
if ($row['alias_name']='localhost') {
?>
<input onmouseover='this.src="assets/icons/play_movie.png"'
onmouseout='this.src="movies/coverart/<?php echo $row['art']; ?>"'
type="image" src="movies/coverart/<?php echo $row['art']; ?>"
style="border: none" height="150" width="110" />
<?php
}else{
?>
<input onmouseover='this.src="assets/icons/play_movie.png"'
onmouseout='this.src="http://<?php echo $row['ip_address']; ?>/<?php echo $row['alias_name']; ?>/coverart/<?php echo $row['art']; ?>"'
type="image" src="http://<?php echo $row['ip_address']; ?>/<?php echo $row['alias_name']; ?>/coverart/<?php echo $row['art']; ?>"
style="border: none" height="150" width="110" />
<?php
?>
When the records are pulled, it seems like only the first part of the if / else statement is being applied to every record that is being pulled. The problem is if I've got records like the following:
Record one - (file on the host computer)
needs to be displayed from the condition
src="movies/coverart/<?php echo $row['art']; ?>"
Record two - (file on networked external hard drive)
needs to be displayed from the condition
src="http://<?php echo $row['ip_address']; ?>/<?php echo $row['alias_name']; ?>/coverart/<?php echo $row['art']; ?>
The way it's coded now, only record one will display the image (record two will not display the image). If I swap the order of the conditions, only record two will display the image (record one will not display the image).
How do I get both record one and record two to display the image when both appear on the same page from a single search query?
If I still did not explain it well enough, please let me know and I will try and do better. Again, thank you for your help.
Maybe you are looking for
-
also an error msg appears wanting to close Hdspa modem if I ignore this msg I can continue.If I respond to this msg firefox will close as modem disconnects.Also if u don't watgh out u can be typing over previously typed inputted data as the cursor dr
-
Task URL causing error in SharePoint Designer
Hi I am creating a workflow in designer and I have a step to send out an email. In the email I am inputting a Hyperlink where the user can click on and directly go to the task to approve. I type the description or text to be displayed and put the ful
-
IPad photo issues with third party apps
Up until recently I've had no problem with the issue I'm about to describe. When I download my raw format photos from my camera using the SD card reader I cannot view full photos in any third party apps such as the Photoshop app or any other I've tri
-
Hello In Warehouse Builder Browser I have one Process Flow with Status Busy. I have restarded the whole server and status is still Busy. Through Oracle Workflow I try to Find Active Processes and there just is no one. Why is my Process Flow still Bus
-
Hi guys, I have a curious question. Sounds a bit silly and highly disappointed if Illustrator is actually not capable of doing this. Hopefully I have missed something. I have an AI doc that has grown so large that saving it now is a major effort so t