SELECT CASE IN PL/SQL
I NEED TO KNOW HOW TO RUN IN PL THE STATEMENT select case
when ...
thanks
Hi
SELECT with a CASE statement will not work in 8i when using
static SQL. However if you are using dynamic SQL to execute it,
then it will be fine. This is because the dynamic SQL statement
is passed to the SQL engine for executing wheras static SQL is
compiled by the PL/SQL compiler, which does not understand the
complete SQL syntax.
This will be fixed in 9i as well as PL/SQL in 9i also includes
the CASE statement itself (outside of SQL).
Guido
Similar Messages
-
FDM Integration script - Selecting the Period from SQL based on FDM PoV
Hi,
I want query SQL Period Column for the month based on the FDM PoV, can or has anyone a sample script of how this is can be achieved?
My script when run comes back with "No records to load" - msg in my script. Let me know if you can spot anything obvious that's causing this in my script.
SQL table
EVENT YEAR Period Entity Ccy Acc ICP Value Product
Actual
FY14
May
HME_AT
EUR
ws_inp
NULL
39
HRX537C2VKEA
Actual
FY14
May
HME_AT
EUR
ws_inp
NULL
3
HS2411Z1E
Dim objSS 'ADODB.Connection
Dim strSQL 'SQL string
Dim strSelectPer 'FDM Period
Dim strCurFDMYear'FDM Year
Dim rs 'SQL Recordset
Dim rsAppend 'FDM tTB table append rs object
Dim recordCount
Dim sWhere
Dim sSelect
'Initialize objects
Set cnSS = CreateObject("ADODB.Connection")
Set rs = CreateObject("ADODB.Recordset")
Set rsAppend = DW.DataAccess.farsTable(strWorkTableName)
'Get Current POV Period And Year And determine HFM Select Year
strSelectPer = Left((RES.PstrPer), 3)
strCurFDMYear = Right(RES.PstrPer, 4)
Select Case UCase(strSelectPer)
Case "APR", "MAY", "JUN", "JUL", "AUG", "SEP", "OCT", "NOV", "DEC"
strSelectYear = strCurFDMYear + 1
Case "JAN", "FEB", "MAR"
strSelectYear = strCurFDMYear
End Select
'Watch with this as it can cause looping
On Error Resume Next
Err.clear
'Connect to SQL database
'cnSS.Open "Driver=SQL Server;Server=EHEINTRADCG\EHEINTRADCG;Database=dw_foundation;UID=hypdb"
cnSS.Open "Driver=SQL Server;Server=EHEINTRADCG\EHEINTRADCG;Database=ODI_WORK_MARS;UID=hypdb"
'Connect to SQL Server database
cnSS.CommandTimeout = 1200
'Keep the error message handling in for testing but will probably need to write
'to a log if running in an overnight batch
'Error Handling
If Err.Number <> 0 Then
' An exception occurred
RES.PlngActionType = 2
RES.PstrActionValue = Err.Description & Chr(10) & "Unable to connect to SQL Data Source"
Err.clear
Set cnSS = Nothing
FinAllLocs_Conv = False
Exit Function
End If
'Create query String
strSQL = strSQL & "From ODI_WORK_MARS.dbo.TMP_HFM_DATA_EXTRACT_TIN1 "
strSQL = sWhere & " And YearID = '" & strSelectYear & "' And PeriodID = '" & strSelectPer & "'"
'Get data
rs.Open strSQL, cnSS
' Check For data
If rs.bof And rs.eof Then
RES.PlngActionType = 2
RES.PstrActionValue = "No Records to load!"
Exit Function
End If
' RecordCount = 0
'Loop through records and append to FDM tTB table in location's DB
If Not rs.bof And Not rs.eof Then
Do While Not rs.eof
'Create the record
rsAppend.AddNew
rsAppend.Fields("PartitionKey") = RES.PlngLocKey ' Location ID
rsAppend.Fields("CatKey") = RES.PlngCatKey 'Current Category ID
rsAppend.Fields("PeriodKey") = RES.PdtePerKey 'Current Period ID
rsAppend.Fields("DataView") = "YTD" 'Data View ID
rsAppend.Fields("CalcAcctType") = 9 'Input data indicator
rsAppend.Fields("Entity") = rs.fields("Entity").Value ' Entity/Genpo ID
rsAppend.Fields("Account")= rs.fields("Account").Value 'Account ID
rsAppend.Fields("ICP") = rs.fields("Inter_Company_Entity_HFM").Value ' Inter-Co/Destination
rsAppend.Fields("Amount") = rs.fields("Value").Value ' Data Value ID
rsAppend.Update
RecordCount = Recordcount + 1
rs.movenext
Loop
End If
'Records loaded
RES.PlngActionType = 2
RES.PstrActionValue = "SQL Import successful! " & RecordCount
'Assign Return value
SAP_HFM = True
End FunctionHi,
the easiest way to check it is to redirect your SQL query to text file and then execute in a SQL tool.
You should write the value of strSQL (which actually seems to have missing the SELECT clause)
In any case, your SQL statement seems to be incomplete:
strSQL = strSQL & "From ODI_WORK_MARS.dbo.TMP_HFM_DATA_EXTRACT_TIN1 "
strSQL = sWhere & " And YearID = '" & strSelectYear & "' And PeriodID = '" & strSelectPer & "'"
- You have not initialized strSQL with SELECT clause (maybe sSelect?)
- You have not initialized sWhere with WHERE clause
In addition to this, your source year is in FYYY format while you are taking year from POV as YYYY.
(...And YearID = 2014 while in your table you have FY14)
After you check this, get the SQL statement, review it, and try to launch against your source DB in a SQL tool.
Regards -
Nested CASE expressions in SQL Server 2008 R2
Hi, For some reason when I use the below CASE expression in my SELECT statement I get duplicate records.
CASE WHEN <Condition 1> THEN <Expression 1>
WHEN <Condition 2> THEN <Expression 2>
WHEN <Condition 3> THEN <Expression 3>
WHEN <Condition 4> THEN <Expression 4>
END AS CaseResult
Also tried using coalesce with no luck. How to write a nested CASE expression which would yield just one expression. In case if I have to combine 2 different Expressions for 1 record, Is there a way to merge the 2 Expressions writing CASE
expression something like below.
STUFF ((SELECT ',' + CASE WHEN <Condition 1> THEN <Expression 1>
WHEN <Condition 2> THEN <Expression 2>
WHEN <Condition 3> THEN <Expression 3>
WHEN <Condition 4> THEN <Expression 4>
END
FOR XML PATH(''), ROOT('MyString'), TYPE).value('/MyString[1]','VARCHAR(MAX)'), 1, 1,'') AS CaseResult
--ResultSet
CaseResult
<Expression 1, Expression 2>
I am using SQL Server 2008 R2. Thanks in advance.......
IoneHi, For some reason when I use the below CASE expression in my SELECT statement I get duplicate records. Also tried using coalesce with no luck. How to write a nested CASE expression which would yeild just one expression. In case if I have to combine 2 different
Expressions for 1 record, Is there a way to merge the 2 Expressions writing CASE expression something like below in SQL Server 2008 R2.
CASE WHEN <Condition 1> THEN <Expression 1>
WHEN <Condition 2> THEN <Expression 2>
WHEN <Condition 3> THEN <Expression 3>
WHEN <Condition 4> THEN <Expression 4>
END AS CaseResultSTUFF ((SELECT ',' + CASE WHEN <Condition 1> THEN <Expression 1>
WHEN <Condition 2> THEN <Expression 2>
WHEN <Condition 3> THEN <Expression 3>
WHEN <Condition 4> THEN <Expression 4>
END
FOR XML PATH(''), ROOT('MyString'), TYPE).value('/MyString[1]'<span clas
Ione -
Using a scalar user defined function in a select case statement
I have a simple select statement below and I want to have a case statement for some conditions based on the result of the udf returned value. I then want the returned value from that specific case statement to be returned where i have indicated 'DISPLAY
ZIPCODE' below.
SELECT
CASE
WHEN (SELECT Top 1 ZipCode FROM ufn_GetAddressByBusinessEntityIDandAddressTypeID(table1.BusinessEntityID,712) IS NOT NULL THEN 'DISPLAY ZIPCODE'
WHEN (SELECT Top 1 ZipCode FROM ufn_GetAddressByBusinessEntityIDandAddressTypeID(table1.BusinessEntityID,714) as r) IS NOT NULL THEN 'DISPLAY ZIPCODE'
ELSE NULL
END as Zipcode,
FROM
table1SELECT COALESCE(ufn_GetAddressByBusinessEntityIDandAddressTypeID(table1.BusinessEntityID,712),ufn_GetAddressByBusinessEntityIDandAddressTypeID(table1.BusinessEntityID,712)) AS Zipcode
FROM table1
Nope. This is two function calls. coalesce(a, b, c, ...) is just syntatic sugar for
CASE WHEN a IS NOT NULL THEN a
WHEN b IS NOT NULL THEN b
WHEN c IS NOT NULL THEN c
END
But if you use isnull it's a different matter. (But isnull() permits two arguments.)
Erland Sommarskog, SQL Server MVP, [email protected] -
Hi,
I'm trying to limit values for my dashboard prompt, but with condition.
I have market channel as the first prompt, and customer as the second prompt. If market channel is, let's say, 'OEM', then I want to limit the second prompt only for specific customers (not all OEM). So as the other market channel, I want to pick only some customers for each of them. This is because the measure applied to only these specific customers.
Thanks in advance.
GTtHEHi,
Thanku for reply.
I used the same approach what did u reply. But still i am facing the similar issue once i say ok to the query.
It is showing the following error:-
Error Codes: OPR4ONWY:U9IM8TAC:OI2DL65P:OI2DL65P
State: HY000. Code: 10058. [NQODBC] [SQL_STATE: HY000] [nQSError: 10058] A general error has occurred. [nQSError: 27002] Near <,>: Syntax error [nQSError: 26012] . (HY000)
SQL Issued: {call NQSGetQueryColumnInfo('SELECT CASE WHEN ''MGMT $''=''MGMT $'' THEN SR_QUOTA_ACHIV_AGGR.MGMT_DOLLARS_MTD_AMT ELSE SR_QUOTA_ACHIV_AGGR.LGL_DOLLARS_MTD_AMT, GEO_DIM.AREA, GEO_DIM.AREA_DESC, ORDER_SPLIT.BOOKED_DT, ORDER_SPLIT.ORD_SHIP_TO_SITE_CITY, ORDER_SPLIT.ORD_SHIP_TO_SITE_NBR, ORDER_SPLIT.ORD_SOLD_TO_SITE_CITY, ORDER_SPLIT.ORD_SOLD_TO_SITE_NBR, SR_QUOTA_ACHIV_AGGR.PROD_LINE_CD, SR_QUOTA_ACHIV_AGGR.QUOTA_CREDIT_COUNTRY_KEY, SR_QUOTA_ACHIV_AGGR.SALES_ORG_ID FROM ROAD_RUNNER')}
SQL Issued: SELECT CASE WHEN 'MGMT $'='MGMT $' THEN SR_QUOTA_ACHIV_AGGR.MGMT_DOLLARS_MTD_AMT ELSE SR_QUOTA_ACHIV_AGGR.LGL_DOLLARS_MTD_AMT, GEO_DIM.AREA, GEO_DIM.AREA_DESC, ORDER_SPLIT.BOOKED_DT, ORDER_SPLIT.ORD_SHIP_TO_SITE_CITY, ORDER_SPLIT.ORD_SHIP_TO_SITE_NBR, ORDER_SPLIT.ORD_SOLD_TO_SITE_CITY, ORDER_SPLIT.ORD_SOLD_TO_SITE_NBR, SR_QUOTA_ACHIV_AGGR.PROD_LINE_CD, SR_QUOTA_ACHIV_AGGR.QUOTA_CREDIT_COUNTRY_KEY, SR_QUOTA_ACHIV_AGGR.SALES_ORG_ID FROM ROAD_RUNNER
Thanks -
Hi all,
I've this problem: insert into Table_A some values from Table_B... with one derivated/calculated filed.
Example
INSERT INTO Table_A (id_part, vendtype, origin, proven, desc)
SELECT id_p, vendt, origin, proven, <calculate/derivated_field_desc>
FROM Table_BThe rules for calculate the field desc inserted on Table_A are 1. IF vendt='V' AND origin='N' AND proven!='04' THEN ---> desc='TRANSFER'
2. IF vendt='M' AND origin='N' AND proven!='04' THEN ---> desc='IMPORTED'
3. IF proven='04' THEN ---> desc='BAD'So what I use in <calculate/derivated_field_desc> on my INSERT INTO statement??
Can I use a SELECT CASE WHEN... or only DECODE is a right solution?
Edited by: trebbia on 15-nov-2010 12.51Ok,
I prefer use select case when... because trasform my rules in DECODE statement is more difficult
So I write: INSERT INTO Table_A (id_part, vendtype, origin, proven, desc)
SELECT id_p, vendt, origin, proven, SELECT CASE WHEN vendt='V' AND origin='N' AND proven!='04' THEN 'TRANSFER'
WHEN vendt='M' AND origin='N' AND proven!='04' THEN 'IMPORTED'
WHEN proven='04 THEN 'BAD'
END
FROM Table_BObtain this error:
40/56 PL/SQL: ORA-00936: missing expression
33/1 PL/SQL: SQL Statement ignored
PS: I use '<' '>' and not '!=' in my code... here not prompted correctly '<''>'
Edited by: trebbia on 15-nov-2010 13.04
Edited by: trebbia on 15-nov-2010 13.06 -
SELECT CASE WHEN not working?
Hello, can't figure out why the following statement continues to return NULL values and seems to not recognize my case when portion?...
INSERT tbl_Main
select OrderID
,(select
case
when (b.OrderValue is null or b.OrderValue = '') then 'Y'
else b.OrderValue
end
from tbl_OrderDetails b where b.OrderID = a.OrderID and b.DetailID = '7')
AS OrderStatus
from tbl_Order a
Thanks in advanced.Please post DDL, so that people do not have to guess what the keys, constraints, Declarative Referential Integrity, data types, etc. in your schema are. Learn how to follow ISO-11179 data element naming conventions and formatting rules. Temporal data should
use ISO-8601 formats. Code should be in Standard SQL as much as possible and not local dialect.
This is minimal polite behavior on SQL forums.
1. The use of the “tbl-” prefix is a design flaw called “tibbling” and people will laugh at you for it.
2. Do not nest selects inside a select list; the performance stinks.
3. Why do you think “A”, "D” etc are good aliases that will make maintaining this code easier? Noobs do this is match the names of tape drives on old hardware!
4. Why do you think that treating a NULL and an empty string as the same is a good idea? Use a CHECK (order_value <> '').
My guess is you could write this instead:
INSERT INTO Orders
SELECT order_id, COALESCE (D.order_value, 'Y') AS order_status
FROM Order_Details AS D
WHERE D.order_id = Orders.order_id
AND D.detail_id = '7')
AS order_status;
But this still smells bad. A status is a state of being so it has a temporal component. Order details do not usually have an id; the item identifier (EAN, UPC, SKU, or whatever) is used.
--CELKO-- Books in Celko Series for Morgan-Kaufmann Publishing: Analytics and OLAP in SQL / Data and Databases: Concepts in Practice Data / Measurements and Standards in SQL SQL for Smarties / SQL Programming Style / SQL Puzzles and Answers / Thinking
in Sets / Trees and Hierarchies in SQL -
May you check this simple select case...
Guys, please, can you check this stupid code? I'm totally shattered and maybe I don't see the simple thing...
with cte as (
SELECT CORE FROM IMPORTOIL group by core)
,cte2 as
(select core , mps, technology
from cte xx right join GeneratorTypo gt on xx.core=gt.mps)
select core, mps, technology , case core when null then 'Import ' else technology end from cte2
even if I got several core NULL it retrieve for the select case only the technology and never the 'Import'. Pratically, if ( I miss 2012 wit the simple iif) the core is null write the same value that there is in technology otherwise write 'Import'...what's
wrong with that?Please post DDL, so that people do not have to guess what the keys, constraints, Declarative Referential Integrity, data types, etc. in your schema are. Learn how to follow ISO-11179 data element naming conventions and formatting rules. Nothing here is correct!
Temporal data should use ISO-8601 formats. Code should be in Standard SQL as much as possible and not local dialect.
This is minimal polite behavior on SQL forums. You also need to learn the syntax for a CASE expression:
CASE WHEN core IS NULL THEN 'IMPORT ' ELSE technology END
The CASE expression is an *expression* and not a control statement; that is, it returns a value of one data type. SQL-92 stole the idea and the syntax from the ADA programming language. Here is the BNF for a <case specification>:
<case specification> ::= <simple case> | <searched case>
<simple case> ::=
CASE <case operand>
<simple when clause>...
[<else clause>]
END
<searched case> ::=
CASE
<searched when clause>...
[<else clause>]
END
<simple when clause> ::= WHEN <when operand> THEN <result>
<searched when clause> ::= WHEN <search condition> THEN <result>
<else clause> ::= ELSE <result>
<case operand> ::= <value expression>
<when operand> ::= <value expression>
<result> ::= <result expression> | NULL
<result expression> ::= <value expression>
The searched CASE expression is probably the most used version of the expression. The WHEN ... THEN ... clauses are executed in left to right order. The first WHEN clause that tests TRUE returns the value given in its THEN clause. And, yes, you can nest CASE
expressions inside each other. If no explicit ELSE clause is given for the CASE expression, then the database will insert a default ELSE NULL clause. If you want to return a NULL in a THEN clause, then you must use a CAST (NULL AS <data type>) expression.
I recommend always giving the ELSE clause, so that you can change it later when you find something explicit to return.
The <simple case expression> is defined as a searched CASE expression in which all the WHEN clauses are made into equality comparisons against the <case operand>. For example
CASE iso_sex_code
WHEN 0 THEN 'Unknown'
WHEN 1 THEN 'Male'
WHEN 2 THEN 'Female'
WHEN 9 THEN 'N/A'
ELSE NULL END
could also be written as:
CASE
WHEN iso_sex_code = 0 THEN 'Unknown'
WHEN iso_sex_code = 1 THEN 'Male'
WHEN iso_sex_code = 2 THEN 'Female'
WHEN iso_sex_code = 9 THEN 'N/A'
ELSE NULL END
There is a gimmick in this definition, however. The expression
CASE foo
WHEN 1 THEN 'bar'
WHEN NULL THEN 'no bar'
END
becomes
CASE WHEN foo = 1 THEN 'bar'
WHEN foo = NULL THEN 'no_bar' -- error!
ELSE NULL END
The second WHEN clause is always UNKNOWN.
The SQL-92 Standard defines other functions in terms of the CASE expression, which makes the language a bit more compact and easier to implement. For example, the COALESCE () function can be defined for one or two expressions by
1) COALESCE (<value exp #1>) is equivalent to (<value exp #1>)
2) COALESCE (<value exp #1>, <value exp #2>) is equivalent to
CASE WHEN <value exp #1> IS NOT NULL
THEN <value exp #1>
ELSE <value exp #2> END
then we can recursively define it for (n) expressions, where (n >= 3), in the list by
COALESCE (<value exp #1>, <value exp #2>, . . ., n), as equivalent to:
CASE WHEN <value exp #1> IS NOT NULL
THEN <value exp #1>
ELSE COALESCE (<value exp #2>, . . ., n)
END
Likewise, NULLIF (<value exp #1>, <value exp #2>) is equivalent to:
CASE WHEN <value exp #1> = <value exp #2>
THEN NULL
ELSE <value exp #1> END
It is important to be sure that you have a THEN or ELSE clause with a data type that the compiler can find to determine the highest data type for the expression.
A trick in the WHERE clause is use it for a complex predicate with material implications.
WHERE CASE
WHEN <search condition #1>
THEN 1
WHEN <search condition #2>
THEN 1
ELSE 0 END = 1
Gert-Jan Strik posted some exampels of how ISNULL() and COALESCE() on 2004 Aug 19
CREATE TABLE #t(a CHAR(1));
INSERT INTO #t VALUES (NULL);
SELECT ISNULL(a,'abc') FROM #t;
SELECT COALESCE(a, 'abc') FROM #t;
DROP TABLE #t;
He always use COALESCE, with the exception of the following type of
situation, because of its performance consequences:
SELECT ...,
ISNULL((SELECT COUNT(*) -- or other aggregate
FROM B
WHERE B.key = A.key), 0)
FROM A;
Likewise, Alejandro Mesa came up with this example:
SELECT 13 / COALESCE(CAST(NULL AS INTEGER), 2.00); -- promote to highest type (decimal)
SELECT 13 / ISNULL(CAST(NULL AS INTEGER), 2.00); -- promote to first type (integer)
>> if (I miss 2012 with the simple iif) the core is null write the same value that there is in technology otherwise write 'Import'... what's wrong with that? <<
Why do you want to write non_ANSI/ISO dialect? Do you like your spreadsheets that much? :(
--CELKO-- Books in Celko Series for Morgan-Kaufmann Publishing: Analytics and OLAP in SQL / Data and Databases: Concepts in Practice Data / Measurements and Standards in SQL SQL for Smarties / SQL Programming Style / SQL Puzzles and Answers / Thinking
in Sets / Trees and Hierarchies in SQL -
In any release of SD, if I have a single worksheet containing 10 sqls. Is it possible to place the cursor on any of the sql and run only that sql, yet, append its output to existing output window. I can then select another sql and execute it and keep appending output. In other words, do not clear existing output or start a new output tab.
As it exists today (in any release), I can either 'run script' which does append, but it executes all the sql (non-selective). Alternately, I can 'run statement' to selectively run a single sql, but it will clear the output window (or if pinned), start a new one. None of this is what I want.
Thank you.Select the query you want to run. Execute it via F5. Then highlight the next query and repeat.
The output will append to the Script Output panel.
There's no way to get 2 queries to share a grid, unless you were to run them as a single query a la UNION. -
Can anyone suggest a select case statement in place of my if statements?
I am having a little trouble switching my if statements to select case. Any help would be appreciated
Option Strict On
Option Explicit On
Public Class Form1
Private Player1 As String
Private Player2 As String
Private Player1Wins As Integer = 1
Private Player2Wins As Integer = 1
Private Tie As Integer = 1
' Close the program
Private Sub btnExit_Click(sender As Object, e As EventArgs) Handles btnExit.Click
Me.Close()
End Sub
' ask for players names
Private Sub frmMainForm_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Player1 = InputBox("Enter Player 1's Name: ")
lblPlayer1.Text = (Player1 + "'s Score:")
Player2 = InputBox("Enter Player 2's Name:")
lblPlayer2.Text = (Player2 + "'s Score:")
End Sub
Private Sub btnRoll_Click(sender As Object, e As EventArgs) Handles btnRoll.Click
' game of rolling dice
Dim randGen As New Random
Dim intNum1 As Integer
Dim intNum2 As Integer
Dim intNum3 As Integer
Dim intNum4 As Integer
Dim intTotal As Integer
Dim intTotal2 As Integer
' make random integer from 1 through 6
intNum1 = randGen.Next(1, 7)
intNum2 = randGen.Next(1, 7)
intNum3 = randGen.Next(1, 7)
intNum4 = randGen.Next(1, 7)
' display the right image in picDie1
Select Case intNum1
Case 1
picDie1.Image = picOneDot.Image
Case 2
picDie1.Image = picTwoDots.Image
Case 3
picDie1.Image = picThreeDots.Image
Case 4
picDie1.Image = picFourDots.Image
Case 5
picDie1.Image = picFiveDots.Image
Case 6
picDie1.Image = picSixDots.Image
End Select
' display the right image in picDie2
Select Case intNum2
Case 1
picDie2.Image = picOneDot.Image
Case 2
picDie2.Image = picTwoDots.Image
Case 3
picDie2.Image = picThreeDots.Image
Case 4
picDie2.Image = picFourDots.Image
Case 5
picDie2.Image = picFiveDots.Image
Case 6
picDie2.Image = picSixDots.Image
End Select
' display the right image in picDie3
Select Case intNum3
Case 1
picDie3.Image = picOneDot.Image
Case 2
picDie3.Image = picTwoDots.Image
Case 3
picDie3.Image = picThreeDots.Image
Case 4
picDie3.Image = picFourDots.Image
Case 5
picDie3.Image = picFiveDots.Image
Case 6
picDie3.Image = picSixDots.Image
End Select
' display the right image in picDie4
Select Case intNum4
Case 1
picDie4.Image = picOneDot.Image
Case 2
picDie4.Image = picTwoDots.Image
Case 3
picDie4.Image = picThreeDots.Image
Case 4
picDie4.Image = picFourDots.Image
Case 5
picDie4.Image = picFiveDots.Image
Case 6
picDie4.Image = picSixDots.Image
End Select
' calculate and display total number of dots
intTotal = intNum1 + intNum2
lblTotal.Text = intTotal.ToString()
intTotal2 = intNum3 + intNum4
lblTotal2.Text = intTotal2.ToString()
' display the winner
If intTotal > intTotal2 Then
MessageBox.Show("Player1 Wins")
End If
If intTotal2 > intTotal Then
MessageBox.Show("Player2Wins")
End If
If intTotal = intTotal2 Then
MessageBox.Show("Tie")
End If
' display summary information when checkbox is checked
If CheckBox1.Checked = True And
intTotal > intTotal2 Then
lblWins.Text = CStr(Player1Wins)
Player1Wins = Player1Wins + 1
lblScores.Visible = True
End If
If CheckBox1.Checked = True And
intTotal2 > intTotal Then
lblWins2.Text = CStr(Player2Wins)
Player2Wins = Player2Wins + 1
lblScores.Visible = True
End If
If CheckBox1.Checked = True And
intTotal = intTotal2 Then
lblTies.Text = CStr(Tie)
Tie = Tie + 1
lblScores.Visible = True
End If
End Sub
End ClassPut everything into lists. Here is elementary sample to get you started.
Private lofDotImage As New List(Of Image)
Private randGen As New Random
Private picDie() As PictureBox
Private Sub setup()
ReDim picDie(3)
picDie(0).Location = New Point()
picDie(0).Size = New Size()
picDie(1).Location = New Point()
picDie(1).Size = New Size()
picDie(2).Location = New Point()
picDie(2).Size = New Size()
picDie(3).Location = New Point()
picDie(3).Size = New Size()
For _delta As Integer = 0 To 3
picDie(_delta).Visible = True
Me.controls.add(picDie(_delta))
Next _delta
Dim _dice1 As Image = Nothing
Dim _dice2 As Image = Nothing
Dim _dice3 As Image = Nothing
Dim _dice4 As Image = Nothing
Dim _dice5 As Image = Nothing
Dim _dice6 As Image = Nothing
lofDotImage.Add(_dice1)
lofDotImage.Add(_dice2)
lofDotImage.Add(_dice3)
lofDotImage.Add(_dice4)
lofDotImage.Add(_dice5)
lofDotImage.Add(_dice6)
End Sub
Private Sub roll()
Dim _lofRolls As New List(Of Integer)
Dim intScorePlayer1 As Integer = 0
Dim intScorePlayer2 As Integer = 0
For _delta As Integer = 0 To 3
_lofRolls.Add(randGen.Next(1, 7))
If _delta < 2 Then
intScorePlayer1 += _lofRolls(_delta)
Else
intScorePlayer2 += _lofRolls(_delta)
End If
picDie(_delta).Image = lofDotImage(_lofRolls(_delta))
Next _delta
If intScorePlayer1 = intScorePlayer2 Then
MessageBox.Show("Tie")
ElseIf intScorePlayer1 > intScorePlayer2 Then
MessageBox.Show("Player1 Wins")
Else
MessageBox.Show("Player2 Wins")
End If
End Sub
Edit: Also to get better random, seed the random once and generate many times, the more seed is the less random.
Also another tip: When comparing it is easy to check = and <> compared to < or > in my experience, also for only one possible outcome use one main if block instead of many. -
I have a doubt in 'SELECT-CASE'. There is this example of which i have :-
SELECT /*+ rule */ SUM(CASE WHEN age <= 15 THEN cnt ELSE 0 END) "upto 15 Years" ,
SUM(CASE WHEN age >= 16 AND age <= 20 THEN cnt ELSE 0 END) "16-20 Years" ,
SUM(CASE WHEN age >= 21 AND age <= 25 THEN cnt ELSE 0 END) "21-25 Years" ,
SUM(CASE WHEN age >= 26 AND age <= 30 THEN cnt ELSE 0 END) "26-30 Years" ,
SUM(CASE WHEN age >= 31 AND age <= 35 THEN cnt ELSE 0 END) "31-35 Years" ,
SUM(CASE WHEN age >= 36 AND age <= 40 THEN cnt ELSE 0 END) "36-40 Years" ,
SUM(CASE WHEN age >= 41 AND age <= 45 THEN cnt ELSE 0 END) "41-45 Years" ,
SUM(CASE WHEN age >= 46 AND age <= 50 THEN cnt ELSE 0 END) "46-50 Years" ,
SUM(CASE WHEN age >= 51 AND age <= 55 THEN cnt ELSE 0 END) "51-55 Years" ,
SUM(CASE WHEN age >= 56 AND age <= 60 THEN cnt ELSE 0 END) "56-60 Years" ,
SUM(CASE WHEN age >= 61 AND age <= 65 THEN cnt ELSE 0 END) "61-65 Years" ,
SUM(CASE WHEN age >= 66 AND age <= 70 THEN cnt ELSE 0 END) "66-70 Years" ,
SUM(CASE WHEN age > 70 THEN cnt ELSE 0 END) ">70 Years"
FROM
(SELECT /*+ rule */ROUND(MONTHS_BETWEEN(SYSDATE,ca.birthdate)/12) age,COUNT(1) cnt
FROM contract_all co , customer_all ca ,curr_co_status curr
WHERE ca.customer_id = co.customer_id
AND co.co_id = curr.co_id
AND curr.ch_status = 'a'
AND ca.birthdate IS NOT NULL
--AND co.co_activated BETWEEN '01-jan-2004' AND '31-dec-2004'
AND EXISTS ( SELECT 'x' FROM hss_cust_segment hcs
WHERE hcs.prgcode = ca.prgcode
AND hcs.description = 'POST')
GROUP BY ROUND(MONTHS_BETWEEN(SYSDATE,ca.birthdate)/12))
In this the statements on top like this-
SUM(CASE WHEN age >= 16 AND age <= 20 THEN cnt ELSE 0 END) "16-20 Years" ,
how does the increment happen in 'THEN cnt' because we are not doing the increment as such using '+1' kind of thing.
I hope, my question is clear. Please help in solving the doubt.
Regards.Sample data, wrong output and desired output please...
I tried with this and it seems right...
WITH ca as (
select to_date('26-9-1990') birthdate from dual union all
select to_date('26-9-1989') birthdate from dual union all
select to_date('26-9-1974') birthdate from dual
SELECT /*+ rule */ SUM(CASE WHEN age <= 15 THEN cnt ELSE 0 END) "upto 15 Years" ,
SUM(CASE WHEN age >= 16 AND age <= 20 THEN cnt ELSE 0 END) "16-20 Years" ,
SUM(CASE WHEN age >= 21 AND age <= 25 THEN cnt ELSE 0 END) "21-25 Years" ,
SUM(CASE WHEN age >= 26 AND age <= 30 THEN cnt ELSE 0 END) "26-30 Years" ,
SUM(CASE WHEN age >= 31 AND age <= 35 THEN cnt ELSE 0 END) "31-35 Years" ,
SUM(CASE WHEN age >= 36 AND age <= 40 THEN cnt ELSE 0 END) "36-40 Years" ,
SUM(CASE WHEN age >= 41 AND age <= 45 THEN cnt ELSE 0 END) "41-45 Years" ,
SUM(CASE WHEN age >= 46 AND age <= 50 THEN cnt ELSE 0 END) "46-50 Years" ,
SUM(CASE WHEN age >= 51 AND age <= 55 THEN cnt ELSE 0 END) "51-55 Years" ,
SUM(CASE WHEN age >= 56 AND age <= 60 THEN cnt ELSE 0 END) "56-60 Years" ,
SUM(CASE WHEN age >= 61 AND age <= 65 THEN cnt ELSE 0 END) "61-65 Years" ,
SUM(CASE WHEN age >= 66 AND age <= 70 THEN cnt ELSE 0 END) "66-70 Years" ,
SUM(CASE WHEN age > 70 THEN cnt ELSE 0 END) ">70 Years"
FROM ( SELECT /*+ rule */ ROUND(MONTHS_BETWEEN(SYSDATE,ca.birthdate)/12) age, COUNT(1) cnt
FROM ca
GROUP BY ROUND(MONTHS_BETWEEN(SYSDATE,ca.birthdate)/12) )
upto 15 Years 16-20 Years 21-25 Years 26-30 Years 31-35 Years 36-40 Years 41-45 Years 46-50 Years 51-55 Years 56-60 Years 61-65 Years 66-70 Years >70 Years
0 2 0 0 1 0 0 0 0 0 0 0 0
1 rows selectedNH. -
I have not used queries which use 'SELECT-CASE' but i have seen a query like as below:-
SELECT /*+ rule */ SUM(CASE WHEN age <= 15 THEN cnt ELSE 0 END) "upto 15 Years" ,
SUM(CASE WHEN age >= 16 AND age <= 20 THEN cnt ELSE 0 END) "16-20 Years" ,
SUM(CASE WHEN age >= 21 AND age <= 25 THEN cnt ELSE 0 END) "21-25 Years" ,
SUM(CASE WHEN age >= 26 AND age <= 30 THEN cnt ELSE 0 END) "26-30 Years" ,
SUM(CASE WHEN age >= 31 AND age <= 35 THEN cnt ELSE 0 END) "31-35 Years" ,
SUM(CASE WHEN age >= 36 AND age <= 40 THEN cnt ELSE 0 END) "36-40 Years" ,
SUM(CASE WHEN age >= 41 AND age <= 45 THEN cnt ELSE 0 END) "41-45 Years" ,
SUM(CASE WHEN age >= 46 AND age <= 50 THEN cnt ELSE 0 END) "46-50 Years" ,
SUM(CASE WHEN age >= 51 AND age <= 55 THEN cnt ELSE 0 END) "51-55 Years" ,
SUM(CASE WHEN age >= 56 AND age <= 60 THEN cnt ELSE 0 END) "56-60 Years" ,
SUM(CASE WHEN age >= 61 AND age <= 65 THEN cnt ELSE 0 END) "61-65 Years" ,
SUM(CASE WHEN age >= 66 AND age <= 70 THEN cnt ELSE 0 END) "66-70 Years" ,
SUM(CASE WHEN age > 70 THEN cnt ELSE 0 END) ">70 Years"
FROM
(SELECT /*+ rule */ROUND(MONTHS_BETWEEN(SYSDATE,ca.birthdate)/12) age,COUNT(1) cnt
FROM contract_all co , customer_all ca ,curr_co_status curr
WHERE ca.customer_id = co.customer_id
AND co.co_id = curr.co_id
AND curr.ch_status = 'a'
AND ca.birthdate IS NOT NULL
--AND co.co_activated BETWEEN '01-jan-2004' AND '31-dec-2004'
AND EXISTS ( SELECT 'x' FROM hss_cust_segment hcs
WHERE hcs.prgcode = ca.prgcode
AND hcs.description = 'POST')
GROUP BY ROUND(MONTHS_BETWEEN(SYSDATE,ca.birthdate)/12))
Please tell a bit, how this works.
I hope, my question is clear. Please help in solving the doubt.
Regards.CASE statement works the same way as DECODE except that the later cannot use an operator. Think of CASE statement as having an IF...THEN...ELSE statement in you SELECT predicates.
-
Select query inside PL/SQL block.
Hello Experts,
I am just a beginner with PL/SQL.
If I write a select query from client like SQL dev and fire it against a database, it gives me result.
Eg: select * from employee;
Now when I use the same Query inside a PL/SQL block suppose:
Declare
begin
select * from employee;
end;
This gives error on execution, mentioning that an INTO is expected etc...
I have doubts here:
1. Can't I use a plain select inside a PL/SQL block (if so why?)
I know this is kind of very basic question, I tried searching this on the forum but could not find the thread, please redirect me to the link if this is already answered.user8578271 wrote:
Hello Experts,
I am just a beginner with PL/SQL.
If I write a select query from client like SQL dev and fire it against a database, it gives me result.
Eg: select * from employee;
Now when I use the same Query inside a PL/SQL block suppose:
Declare
begin
select * from employee;
end;
This gives error on execution, mentioning that an INTO is expected etc...
I have doubts here:
1. Can't I use a plain select inside a PL/SQL block (if so why?) Because when you run a query in a tool like SQL Developer, or SQL*Plus or TOAD etc. then it opens up a cursor and fetches the data into internal memory structures before displaying it, and that is all done automatically and hidden from you. In PL/SQL, there is no interface to display the results of SQL queries, so you have to specifically tell it what to put the data into.
The syntax is (in basic terms)...
SELECT column1, column2... columnX
INTO variables or record structure
FROM ...Though that can only select a single row of data. If your query returns more than 1 row it will give a TOO_MANY_ROWS exception. If your query returns no rows you will get a NO_DATA_FOUND exception.
If you need to select multiple rows into variables etc., then you would need to "BULK COLLECT" into a collection/array structure, though this takes up valuable memory on the server and shouldn't be used unless necessary (and you understand the implications of doing it). -
Limit users to execute "SELECT" statemes only from SQL Developer
Hi:
Is there a way to control what SQL command can be executed from SQL Developer?
I am trying to limit users to execute "SELECT" statements only from SQL Developer.
I believe SQL*Plus used to have the product profile where I can control what SQL command can be executed from what user.
Thanks in advance.There's nothing special in sqldev to enforce privileges, the database does all that already. See the database documentation on the GRANT and REVOKE statements. Basically, you would only want to grant SELECT privileges to your users...
Have fun,
K. -
Select statements inside a SQL Expression field
Hello
Why cannot we use the Select statements inside a SQL expression field in Crystal Reports ?
Any alternatives for this...
SELECT Top(1) "SomePrivateDatabase"."SPDname" FROM "SomePrivateDatabase"
inner join "Subscriber" on
"Subscriber"."SPDID" = "SomePrivateDatabase"."SPDID"
inner join "UserDetails" on
"UserDetails"."SPDID" = "SubscriberCore"."SPDID"
Regards
Srivatsa
Edited by: Srivatsa Haridas on Dec 3, 2008 12:17 PMHi Srivatsa,
SQL Expressions is something the Database supports. We query the Client engine for a list of functions they make available. If the SQL Statement is not list it's not an option and therefore it won't work.
Your work arounds are to use either a Stored Procedure, this is the most efficient way, all processing is done server side and CR simply waits for the data to format in the report. Another option is to use a
Command Object, use one CO per report so try to get all data within the SQL statement. We simply pass the SQL to the server and wait for the result set, if you get an error it will be the SQL you typed in. Test in a SQL test tool first to confirm you are getting the data correctly.
For more assistance in designing reports please post your report deisgn questions to the Reprot Design forums. I am moving this one to that queue.
Thank you
Don
Maybe you are looking for
-
Upgrade SATA drive for macbook late 2008
Hello!! I am here to ask for help. Let me tell you a bit more about my Mac: Late 2008 silver 13" MacBook 250GB 2GB RAM 2.4GHz IntelCore2Duo DDR3 MB467LL/A, currently at 10.5.8 OSx system (yes I know I need to update the software as well!) I currently
-
How do I make a sub total not count in the TOTAL?
My totals add the sub total figure as though it were an item. How do I get the sub total to not be calculated?
-
I’m encountering problem setting up a wifi wpa2 Enterprise on my Iphone 4s. I set it up using Iphone configuration utility and settings are correct. The problem is that the connection don’t works. I’m sure setting are correct because I set it up the
-
ACWIcon.exe error after Downloading Lenovo software
I recently downloaded software updates from Lenovo. After the download I now receive the following message at startup: ACWI.Icon.exe - Entry Point Not Found The procedure entry point CheckWMAXConnForWLANradioON could not be located in the dynamic li
-
I bought a used donated Macbook 4,1 to dip my toes in the Apple world. The system has the OS X 10.6 operating system but the admin name and/or password that I was given does not work and I have tried every combination that I can imagine. The chari