K-Bits (1) : Interchange the values of two columns
Hi Everyone
I wanted to get started a mechanism of knowledge sharing in the way of a series of threads called “K-Bits” (Knowledge Bits).
In our day to day work, we learn some new things which can be useful for others. However we hardly get a chance to share it with others.
Here is the opportunity to share your knowledge in the form of “K-Bits”.
Here we start with the First Tip of this series.
You might face a situation where you need to interchange the values of 2 columns in an Oracle database table.
E.g. there is a table employee having columns EMPID, FIRST_NAME, LAST_NAME and SALARY. By mistake the values of FIRST_NAME and LAST_NAME have been interchanged. Now you need to bring the data in correct state.
You can think about following few options:
Option-1_
1. Alter table employee and add a new column TEMP_NAME to it.
2. Update the values of LAST_NAME to TEMP_NAME.
3. Update the LAST_NAME with the values of FIRST_NAME.
4. Update the FIRST_NAME with the values of TEMP_NAME.
5. Drop the column TEMP_NAME.
Option-2 (For Oracle version 9i or higher)_
1. Alter table employee and rename LAST_NAME column to TEMP_NAME.
2. Alter table employee and rename column FIRST_NAME to LAST_NAME.
3. Alter table employee and rename column TEMP_NAME to FIRST_NAME.
Probably you can go ahead with any other solution as well. However there is one very simple solution.
Option-3_
Let do it by example:
DROP TABLE EMPLOYEE;
CREATE TBALE EMPLOYEE
EMPID NUMBER
,FIRST_NAME VARCHAR2(30)
,LAST_NAME VARCHAR2(30)
,SALARY NUMBER
INSERT INTO EMPLOYEE VALUES (1,'Tendulkar','Sachin', 10000);
INSERT INTO EMPLOYEE VALUES (1,'Ganguli','Saurabh', 10000);
INSERT INTO EMPLOYEE VALUES (1,'Pathan','Irfan', 10000);
INSERT INTO EMPLOYEE VALUES (1,'Khan','Jaheer', 10000);
INSERT INTO EMPLOYEE VALUES (1,'Agarkar','Ajit', 10000);
INSERT INTO EMPLOYEE VALUES (1,'Dravid','Rahul', 10000);
SELECT *
FROM EMPLOYEE;
UPDATE EMPLOYEE
SET FIRST_NAME = LAST_NAME
,LAST_NAME = FIRST_NAME;
SELECT *
FROM EMPLOYEE; The update statement above solves the purpose. Is not it simple? But how does it work??
For any DML (Insert, Update or Delete) oracle internally fires the row level triggers. You can read more about triggers at
http://download-east.oracle.com/docs/cd/B10501_01/server.920/a96524/c18trigs.htm
and
http://download-east.oracle.com/docs/cd/B10501_01/appdev.920/a96590/adg13trg.htm#431
As you know in row level triggers the values of each column is stored in :OLD and :NEW parameters. For the above UPDATE statement oracle stores the old values of FIRAT_NAME and LAST_NAME in :OLD.FIRST_NAME and :OLD.LAST_NAME parameters respectively and then update FIRST_NAME with :OLD.LAST_NAME and LAST_NAME with :OLD.FIRST_NAME.
Regards
Arun Kumar Gupta
For any DML (Insert, Update or Delete) oracle internally fires the row level triggers.Any pointer to the documentation supporting this ?
Edited by: Saubhik on Dec 7, 2010 5:58 PM
Similar Messages
-
From two given tables, how do you fetch the values from two columns using values from one column(get values from col.A if col.A is not null and get values from col.B if col.A is null)?
Hi,
Use NVL or COALESCE:
NVL (col_a, col_b)
Returns col_a if col_a is not NULL; otherwise, it returns col_b.
Col_a and col_b must have similar (if not identical) datatypes; for example, if col_a is a DATE, then col_b can be another DATE or it can be a TIMESTAMP, but it can't be a VARCHAR2.
For more about NVL and COALESCE, see the SQL Language manual: http://docs.oracle.com/cd/E11882_01/server.112/e26088/functions119.htm#sthref1310
I hope this answers your question.
If not, post a little sample data (CREATE TABLE and INSERT statements, relevant columns only) for all tables involved, and also post the results you want from that data.
Explain, using specific examples, how you get those results from that data.
Always say which version of Oracle you're using (e.g., 11.2.0.2.0).
See the forum FAQ: https://forums.oracle.com/message/9362002 -
Concatinating the values of two columns ???
Hi,
Can anyone help me out in concatenating the values of two columns ??
Please ASAP...
Thanks>
What's wrong with
select (col X || '-'|| Col y ) as Z from xyz_table;
test@ora>
test@ora>
test@ora> --
test@ora> with xyz_table as (
2 select 1 as col from dual)
3 --
4 select (col X || '-'|| Col y ) as Z from xyz_table;
select (col X || '-'|| Col y ) as Z from xyz_table
ERROR at line 4:
ORA-00907: missing right parenthesis
test@ora>
test@ora>
test@ora> --
test@ora> with xyz_table as (
2 select 1 as x, 2 as y from dual)
3 --
4 select (col X || '-'|| Col y ) as Z from xyz_table;
select (col X || '-'|| Col y ) as Z from xyz_table
ERROR at line 4:
ORA-00907: missing right parenthesis
test@ora>
test@ora>
test@ora> -- ==================================================
test@ora> --
test@ora> with xyz_table as (
2 select 1 as col from dual)
3 --
4 select (col || '-'|| Col) as Z from xyz_table;
Z
1-1
1 row selected.
test@ora>
test@ora>
test@ora> --
test@ora> with xyz_table as (
2 select 1 as x, 2 as y from dual)
3 --
4 select (X || '-'|| y ) as Z from xyz_table;
Z
1-2
1 row selected.
test@ora>
test@ora>isotope -
Adding the value of two columns and place to 3rd column in jtable
hi all,
i have table with 3 columns with rows
say for example --loan, interest, total
i want add loan+interest and place into total column.
how can i do this?
thanks in advance
dayaUse a TableModelListener:
http://forum.java.sun.com/thread.jspa?forumID=57&threadID=566133 -
In BADi , How to pass the values between two Method
Hi Experts,
We have two methods in BADis. How to pass the value between two Methods. Can you guys explain me out with one example...
Thanks & Regards,
Sivakumar SHi Sivakumar!
Create a function group.
Define global data (there is a similiar menu point to jump to the top include).
Create one or two function modules, with which you can read and write the global data.
In your BADI methods you can access the global data with help of your function modules. It will stay in memory through the whole transaction.
Regards,
Christian -
I want to spit cell the value into two separate columns like f_name & l_nam
Hi Guys,
I have excel data in one cell with ',' separated data.
sample data:
empno ename
121 ravi,kann
232 ram,raman
here ename value in one provided in one cell.
Now i want to spit cell the value into two separate columns like first_name and last_name?
Thanks in advance
-LKwith sample_data as
select 121 empno, 'ravi,kann' ename from dual union all
select 232 empno, 'ram,raman' from dual
select empno,
substr(ename,1,instr(ename,',')-1) first_name,
substr(ename,instr(ename,',')+1) last_name
from sample_data; or with regular expressions:
with sample_data as
select 121 empno, 'ravi,kann' ename from dual union all
select 232 empno, 'ram,raman' from dual
select empno,
regexp_substr(ename,'^[^,]*') first_name,
regexp_substr(ename,'[^,]*$') last_name
from sample_data; Edited by: hm on 04.07.2012 06:22 -
can't get the value from two variables when execute MDX : Anyone who can help ?
================================
with member [Measures].[APGC Replied Volume] as
([Measures].[Question],[Dim Replied By].[Replied By].&[APGC])
member [Measures].[APGC Moderated Volume] as
([Measures].[DashBoard Thread Number],[Dim Moderated By].[Moderated By].&[APGC])
member [Measures].[APGC Answered Volume] as
([Measures].[Question],[Dim Answered By].[Answered By].&[APGC])
SELECT
NON EMPTY
[Measures].[Forum Thread Number],
[Measures].[Reply In24 Hour],
[Measures].[Question],
[Measures].[Deliverale Minute],
[Measures].[Working minutes],
[Measures].[Answered],
[Measures].[1D Answer],
[Measures].[2D Answer],
[Measures].[7D Answer],
[Measures].[APGC Replied Volume],
[Measures].[APGC Moderated Volume],
[Measures].[APGC Answered Volume],
[Measures].[Avg HTR],
[Measures].[Avg HTA],
[Measures].[Total Labor]
} ON COLUMNS,
NON EMPTY { ([Dim Engineer].[SubGroup-Alias].[Alias].ALLMEMBERS ) } DIMENSION PROPERTIES MEMBER_CAPTION, MEMBER_UNIQUE_NAME ON ROWS
FROM (
SELECT ( STRTOMEMBER(@FromDimTimeFiscalYearMonthWeekLastDateDay, CONSTRAINED) : STRTOMEMBER(@ToDimTimeFiscalYearMonthWeekLastDateDay,
CONSTRAINED) ) ON COLUMNS
FROM [O365]) CELL PROPERTIES VALUE, BACK_COLOR, FORE_COLOR, FORMATTED_VALUE, FORMAT_STRING, FONT_NAME, FONT_SIZE, FONT_FLAGSHi Ada,
According to your description, you can't get the member when using the strtomember() function in your MDX. Right?
In Analysis Services, while the member name string provided contains a valid MDX member expression that resolves to a qualified member name, the CONSTRAINED flag requires qualified or unqualified member names in the member name string. Please check if the
variable is a Multidimensional Expressions (MDX)–formatted string.
Reference:
StrToMember (MDX)
If you have any question, please feel free to ask.
Simon Hou
TechNet Community Support -
How to get the difference between two columns in a column group
Hi All,
My first time here and really new to programming. I would like to get the difference between 2 columns that are inside
a column group.
Here is my sample table below: The Column Group is PeriodNumber and can only choose 2. like 1 and 2.. I would like to have a third row which will simply calculate the difference between the amounts in PeriodNumber 1 and 2.
PeriodNumber
Account 1 2
1) Cash 10,000 15,000
2) Receivables 12,000 11,500
3) Equipment 5,000 5,500
Total Assets 27,000 32,000Hi yabgestopa,
From your description, you want to get the difference between two columns in a column group. After testing it in my environment, we can use custom code to achieve your requirement. For more details, you can refer to the following steps:
Copy the custom code below and paste it to your report. (Right-click report>Report Properties>Code)
Dim Shared Num1 As Integer
Dim shared Num2 As Integer
Public Function GetAmount(Amount as Integer, Type as String)
If Type = "1" Then
Num1=Amount
Else
Num2=Amount
End If
Return Amount
End Function
Public Function GetDif()
Return Num1-Num2
End function
Right-click the second column to insert a third column with Outside Group-Right.
Then use the expressions below in the matrix.
=Code.GetAmount(Fields!Amount.Value,Fields!PeriodNumber.Value)
=code.GetAmount(Sum(Fields!Amount.Value),Fields!PeriodNumber.Value)
=Code.GetDif()
The report looks like below.
If you have any questions, please feel free to ask.
Thanks,
Katherine Xiong
Katherine Xiong
TechNet Community Support -
Find the difference between two columns in an ssrs matrix ? MSCRM
Hi All,
I am working in reporting part of our project (On-line MSCRM 2013) & in reporting services.
I am trying to create report using fetch xml based. Below is the snap what we required the result.
Kindly help me, how to get the difference in both column. (Its a matrix table where year is grouped).
We need difference between both year Like (Plan Revenue of 2013 & Plan Revenue of 2014 difference in Plan Revenue Diff section) and same for Actual
Revenue.
https://social.microsoft.com/Forums/en-US/054d5ca4-0d38-4dc6-84a8-88866cc228fe/find-the-difference-between-two-columns-in-an-ssrs-matrix-mscrm?forum=crmdevelopment
Thanks,
Mohammad ShariqueHi Bro,
I used parametrized option for year and done the report,Currently we are getting values in Difference column now i want to show
that value in percentage. How can we show the percentage based on that value. Means i want to show the Difference in Percentage.
Kindly help me i tried but getting some issue. Below i am mentioning the code and snap with result.
Below expression using to showing Plan Revenue in Percentage for year.
=
Sum(IIF(Fields!new_year.Value =Parameters!StartYear.Value,cdec(Fields!new_planrevenueValue.Value/1000), cdec(0)))
- Sum(IIF(Fields!new_year.Value =Parameters!EndYear.Value,cdec(Fields!new_planrevenueValue.Value/1000), cdec(0)))
/IIF(Sum(IIF(Fields!new_year.Value = Parameters!StartYear.Value,cdec(Fields!new_planrevenueValue.Value/1000), cdec(0)))>0,
(Sum(IIF(Fields!new_year.Value = Parameters!StartYear.Value,cdec(Fields!new_planrevenueValue.Value/1000), cdec(0))))
,1)
)*100))
Result issue is as below in snap with highlighted in red colour.
Kindly help me on this issue also :) -
Need to compare values in two columns of one table against values in two columns in another table
Hi, as the title reads, I'm looking for an approach that will allow me to compare values in two columns of one table against values in two columns in another table.
Say, for instance, here are my tables:
Table1:
Server,Login
ABCDEF,JOHN
ABCDEF,JANE
FEDCBA,SEAN
FEDCBA,SHAWN
Table2:
Server,Login
ABCDEF,JOHN
ABCDEF,JANE
FEDCBA,SHAWN
In comparing the two tables, I'd like my query to report the rows in table1 NOT found in table2. In this case, it'll be the 3rd row of table one:
Server,Login
FEDCBA,SEAN
Thanks.create table Table1([Server] varchar(50), Login varchar(50))
Insert into Table1 values ('ABCDEF','JOHN'),('ABCDEF','JANE'),('FEDCBA','SEAN'),('FEDCBA','SHAWN')
create table Table2([Server] varchar(50), Login varchar(50))
Insert into Table2 values ('ABCDEF','JOHN'),('ABCDEF','JANE'), ('FEDCBA','SHAWN')
select [Server] ,Login from Table1
Except
select [Server] ,Login from Table2
select [Server] ,Login from Table1 t1
where not exists(Select 1 from Table2 where t1.[Server] = t1.[Server] AND Login=t1.Login)
drop table Table1,Table2 -
Hi All,
Am using OPENROWSET to load the file data into table, here the problem is i need to map same input value to two different columns of table, As format file doesn't allow the duplicate numbers am unable to insert same value to two columns, please help me to
find a solution for this.
i can use only OPENROWSET because i need to insert some default values also which come based on file. only the problem is how to map same input value to two different columns of table. please give me the suggestions.
Thanks,
SudhakarFrom what you say:
INSERT tbl(col1, col2)
SELECT col1, col1
FROM OPENROWSET(....)
But I guess it is more difficult. You need to give more details. What sort of data source do you have? What does your query look like? The target table?
Erland Sommarskog, SQL Server MVP, [email protected]
Hi Erland,
Thanks for your response
my source file is text file with | symbol separate for ex:
1002|eTab |V101|eTablet|V100|Logic|LT-7|Laptops|SCM
Database table have columns like
column1,column2,column3...etc, now i need to insert same value from input file into two columns for ex:
the eTab value from text file has to be insert into column2 and column3 of
table
we cannot change format file like below one
for the above situation how can we insert eTab into column2 and column3
Thanks,
Sudhakar. -
Sum the lesser of two columns when condition is met
Hi. I need help with creating a formula that will sum the lesser value between two columns when a condition in another column is met.
Example: Sum the lesser value between columns B and C when column A contains "x".
...A...B...C
1.....3.....2
2.x...4....1
3
4.x...2....3
A2 and A4 contain "x". The lesser value between B2 and C2 is 1. The lesser value between B4 and C4 is 2. So 1 + 2 = 3. The sum should be 3.add a new column (let's say columns D) that finds the min of the two columns
=min(B, C)
then use sumif(A, "X", D)
like this:
D1=MIN(B1:C1)
this is shorthand for... select cell D1, then type (or copy and paste from here) the formula:
=MIN(B1:C1)
select cell D1, copy
select column D (by clicking the "D" at the very top of the column), paste
E1=SUMIF(A,"X",D ) -
Update one column while getting the value in another column
Is it possible to in one single SQL statement update two columns in a table while at the same time obtaining the value of another column, on the same row, in the same table, and independently (that is, the update of the columns has nothing to do with the data that I want from another column)*?* Of course, I can do this in two operations, one being a "select" and the other one being an "update", but since I am in the same table and even on the same row, is it really necessary to make TWO database calls? That's why I want to combine the the two SQL-statements, for reasons of presumed effiency.
jsun wrote:
Is it possible to in one single SQL statement update two columns in a table while at the same time obtaining the value of another column, on the same row, in the same table, and independently (that is, the update of the columns has nothing to do with the data that I want from another column)*?* Of course, I can do this in two operations, one being a "select" and the other one being an "update", but since I am in the same table and even on the same row, is it really necessary to make TWO database calls? That's why I want to combine the the two SQL-statements, for reasons of presumed effiency.Two statements != two database calls.
At least not in terms of SQL.
JDBC requires a 'statement' but in SQL (depending on the data source) that can include multiple statements. An obvious example of this is a stored proc but there are other ways as well. -
I am experiencing issue with my SharePoint site , when I am trying to add new Item in List . Error given below :--> 02/03/2015 08:23:36.13 w3wp.exe (0x2E04) 0x07E8 SharePoint Server Logging Correlation Data 9gc5 Verbose Thread change; resetting trace
level override to 0; resetting correlation to e2e9cddc-cf35-4bf8-b4f3-021dc91642da c66c2c17-faaf-4ff9-a414-303aa4b4726b e2e9cddc-cf35-4bf8-b4f3-021dc91642da 02/03/2015 08:23:36.13 w3wp.exe (0x2E04) 0x07E8 Document Management Server Document Management 52od
Medium MetadataNavigationContext Page_InitComplete: No XsltListViewWebPart was found on this page[/sites/00003/Lists/PM%20Project%20Status/NewForm.aspx?RootFolder=&IsDlg=1]. Hiding key filters and downgrading tree functionality to legacy ListViewWebPart(v3)
level for this list. e2e9cddc-cf35-4bf8-b4f3-021dc91642da 02/03/2015 08:23:36.17 w3wp.exe (0x1B94) 0x1A0C SharePoint Server Logging Correlation Data 77a3 Verbose Starting correlation. b4d14aec-5bd4-4fb1-b1e3-589ba337b111 02/03/2015 08:23:36.17 w3wp.exe (0x1B94)
0x1A0C SharePoint Server Logging Correlation Data 77a3 Verbose Ending correlation. b4d14aec-5bd4-4fb1-b1e3-589ba337b111 02/03/2015 08:23:36.31 w3wp.exe (0x2E04) 0x07E8 SharePoint Foundation Database 880i High System.Data.SqlClient.SqlException: Cannot insert
the value NULL into column 'tp_DocId', table 'Content_SP_00003.dbo.AllUserData'; column does not allow nulls. INSERT fails. The statement has been terminated. at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection) at
System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj) at System.Data.SqlClient.TdsParser.Run(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject
stateObj) at System.Data.SqlClient.SqlDataReader.ConsumeMetaData() at System.Data.SqlClient.SqlDataReader.get_MetaData() at System.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds, RunBehavi... e2e9cddc-cf35-4bf8-b4f3-021dc91642da 02/03/2015
08:23:36.31* w3wp.exe (0x2E04) 0x07E8 SharePoint Foundation Database 880i High ...or runBehavior, String resetOptionsString) at System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream,
Boolean async) at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method, DbAsyncResult result) at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior,
RunBehavior runBehavior, Boolean returnStream, String method) at System.Data.SqlClient.SqlCommand.ExecuteReader(CommandBehavior behavior, String method) at System.Data.SqlClient.SqlCommand.ExecuteReader(CommandBehavior behavior) at Microsoft.SharePoint.Utilities.SqlSession.ExecuteReader(SqlCommand
command, CommandBehavior behavior,Are you trying to setup P2P? Could you explain the process you followed completely? By anychance you create the backup and then created the publication?
Regards, Ashwin Menon My Blog - http:\\sqllearnings.com -
How to get all the values in one column of a JTable
How to get all the values in one column of a JTable as a Collection of String.
I don;t want to write a for loop to say getValueAt(row, 1) eg for 2nd column.I don;t want to write a for loop to say getValueAt(row, 1) eg for 2nd column. You could always write a custom TableModel that stores the data in the format you want it. It would probably be about 50 lines of code. Or you could write a loop in 3 lines of code. I'll let you decide which approach you want to take.
Maybe you are looking for
-
Mail for exchange settings on N97
I have a N97 which mail for exchange was working happily on, synchronizing mail, contact's and calendar. The world was a good place! The screen broke and needed replacing on my N97 and I have set up mail for exchange again. Now when it downloads ma
-
If i got an iphone 5 and synced it with my computer, can i get the contract from my iphone 4 to a iphone 5 without upgrading the contract? (So that i will still have the same contract) (I have verizon.)
-
Hi, i am using the SAP B1 - 2005B and Sql Server 2005. I have the taken the back up from other server which is having the same verion and restored in the new one. after the sucessful restoration when i tried to connect the new D/B it shows the fo
-
Firefox works fine. However, my bookmarks toolbar is marked as <empty>. Didn't used to be. I have no idea where they've gone. So rather than dwell on the loss, I thought I'd move ahead by importing the bookmarks I have in Safari over to Firefox. No l
-
Airport base station restarting when attempting to contect to Airport Disk!
Hi All, I have a new AEBS 802.11n - and am trying to set it up to share my external HDD over the network. The airport recognizes the drive and asks me if I'd like to login. I have it set to share drives with it's own password I've set and I've checke