How To Update A Column With The Sum Of Two Columns In A Table
May 9, 2008
I have a simple question that is more about performance on my code for updating a column with the sum of two columns:
Example
Table = dbo.adding
c1 c2 c3Sum
1 2
3 5
4 6
Now if I just simple write
Update dbo.adding
set c3SUM = c1 + c2
This works, but there is a null in c1 or c2 then I know I can write this:
if exists (select * from dbo.adding where c1 is NULL)
Update dbo.adding
set c1 = '0', c3SUM = '0' + c2 where c1 is NULL
if exists (select * from dbo.adding where c2 is NULL)
Update dbo.adding
set c2 = '0', equals = c1 + '0' where c2 is NULL
Update dbo.adding
set c3SUM = c1 + c2
This works as well, but I am not sure how perficient it is being that from my understanding the code will evaluate the table three times and update it based on the criteria. If the table consists of 100,000 rows then this might not be a good solution
Is there a more proficient way to do this... I personally try to as little coding as possible to help increase performance. I know I can make this very complex and declare variables and put everything in a loop, but I personally think that would be less profient..
View 8 Replies
ADVERTISEMENT
Jul 31, 2015
I have a table #vert where I have value column. This data needs to be updated into two channel columns in #hori table based on channel number in #vert table.
CREATE TABLE #Vert (FILTER VARCHAR(3), CHANNEL TINYINT, VALUE TINYINT)
INSERT #Vert Values('ABC', 1, 22),('ABC', 2, 32),('BBC', 1, 12),('BBC', 2, 23),('CAB', 1, 33),('CAB', 2, 44) -- COMBINATION OF FILTER AND CHANNEL IS UNIQUE
CREATE TABLE #Hori (FILTER VARCHAR(3), CHANNEL1 TINYINT, CHANNEL2 TINYINT)
INSERT #Hori Values ('ABC', NULL, NULL),('BBC', NULL, NULL),('CAB', NULL, NULL) -- FILTER IS UNIQUE IN #HORI TABLE
One way to achieve this is to write two update statements. After update, the output you see is my desired output
UPDATE H
SET CHANNEL1= VALUE
FROM #Hori H JOIN #Vert V ON V.FILTER=H.FILTER
WHERE V.CHANNEL=1 -- updates only channel1
UPDATE H
SET CHANNEL2= VALUE
FROM #Hori H JOIN #Vert V ON V.FILTER=H.FILTER
WHERE V.CHANNEL=2 -- updates only channel2
SELECT * FROM #Hori -- this is desired output
my channels number grows in #vert table like 1,2,3,4...and so Channel3, Channel4....so on in #hori table. So I cannot keep writing too many update statements. One other way is to pivot #vert table and do single update into #hori table.
View 5 Replies
View Related
May 30, 2015
I want to compare two columns in the same table called start date and end date for one clientId.if clientId is having continuous refenceid and sartdate and enddate of reference that I don't need any caseopendate but if clientID has new reference id and it's start date is not continuous to its previous reference id then I need to set that start date as caseopendate.
I have table containing 5 columns.
caseid
referenceid
startdate
enddate
caseopendate
[code]...
View 4 Replies
View Related
Jan 22, 2007
Hey ya'll...
I need to create a query that I can run that will allow me to essentially take the first initial and last name and combine them from two columns in one table and update one column with that new data in another table. Example of need:
UPDATE tblLogin.UserName with (first character(tblEmployee.FName)+(tblEmployee.LName)) WHERE tblLogin.EmployeeID = tblEmployee.EmployeeID.
That was TOTALLY pseudo code and I know I'll need a join statement in there somewhere. Both tables reside on the same database, such as this:
dbEMPLOYEE (Database)--> tblLogin (Table)----> UserName (Column)--> tblEmployee (Table)----> FName (Column)----> LName (Column)
Any help would be GREATLY appreciated! Hopefully something soon - this was handed to me a few minutes ago and I have a few minutes to get it done.iSheahan
View 5 Replies
View Related
May 21, 2008
Hi,I have three columns and want to update the third column based on the comparison of first two columns in the same table.For instance:Col1 - val1, val2, val3, val4, val5......Col2 - NULL, NULL, val1, NULL, val2....Col3 - TRUE, TRUE, FALSE, FALSE, FALSE....Thanks for any help.
View 4 Replies
View Related
Jun 14, 2007
Hi,I have table with three columns as belowtable name:expNo(int) name(char) refno(int)I have data as belowNo name refno1 a2 b3 cI need to update the refno with no values I write a query as belowupdate exp set refno=(select no from exp)when i run the query i got error asSubquery returned more than 1 value. This is not permitted when thesubquery follows =, !=, <, <= , >, >= or when the subquery is used asan expression.I need to update one colum with other column value.What is the correct query for this ?Thanks,Mani
View 3 Replies
View Related
Jul 7, 2015
I've got a table with 6 fields :
EmployeeAccess
(MasterID, LoginID, AccessID, Storage1, Storage2, Storage3)
that needs to be updated using the data in the following spreadsheet
NewEmployeeAccessData
(ID, MasterID, AccessID1, LoginID1)
There is a 1:1 relationship between the two tables..I'm trying to code a pair of update statements on the EmployeeAccess table (1 for LoginID, 1 for AccessID) with the following logic:
If LoginID is NULL, then Update LoginID with new LoginID1 value,
If LoginID is not null, and Storage1 is NULL then Update Storage1 with New LoginID1 values
If LoginID is not null, and Storage1 is not NULL and Storage2 is NULL then Update Storage2 with New LoginID1 values
etc etc...
The same applies when trying to populate the AccessID column
If AccessID is NULL, then Update AccessID with new AccessID1 value,
If AccessID is not null, and Storage1 is NULL then Update Storage1 with New AccessID1 values
If AccessID is not null, and Storage1 is not NULL and Storage2 is NULL then Update Storage2 with New AccessID1 values
etc etc.
I have no control over the schema of this table so I'm trying to work the logic on how to update the columns in my table only if the corresponding column data is NULL, else update the next non NULL Storage column.
View 7 Replies
View Related
Apr 8, 2008
I have 4 rows below in file tblTEST, and I want to be able to transfer the CODE from the MAIN location to the INT location (replacing all existing "A" codes), preceeded by an "I".
ID LOC CODE
-- ----- ------
11 MAIN B
11 INT A
22 MAIN C
22 INT A
I want the result to be:
ID LOC CODE
-- ----- ------
11 MAIN B
11 INT IB
22 MAIN C
22 INT IC
I am stumped as to how to do this - any help or advice would be appreciated.
The only thing I've come up with is:
UPDATE S
SET s.code = B.code
FROM tbltest B
LEFT OUTER JOIN tbltest S ON B.id = S.id
WHERE (S.loc = 'INT')
But when I run it, it says "0 rows affected".
View 5 Replies
View Related
Aug 5, 2015
I have a table with 8 columns, I need to update data in multiple columns on this table, this table contains 1 million records, having single update was taking time so I broke the single update into multiple update statements and running multiple update statements in parallel, Each update statement updates different column.
This approach is working fine but I am getting the deadlock error.
Transaction (Process ID 65) was deadlocked on lock | communication buffer resources with another process and has been chosen as the deadlock victim. Rerun the transaction.
I tried with various lock hints but no success.
View 4 Replies
View Related
Nov 15, 2013
I want to update multiple column in one table using with case statement. i need query pls..
stdidnamesubject result marks
1 arun chemistry pass 55
2 alias maths pass 70
3 babau history pass 55
4 basha hindi NULL NULL
5 hussain hindi NULL nULL
6 chandru chemistry NULLNULL
7 mani hindi NULLNULL
8 rajesh history NULLNULL
9 rama chemistry NULLNULL
10 laxman maths NULLNULL
View 2 Replies
View Related
Jan 8, 2007
Hi everyone. I am updating a table with aggregate results for multiplecolumns. Below is an example of how I approached this. It works finebut is pretty slow. Anyone have an idea how to increase performance.Thanks for any help.UPDATE #MyTableSET HireDate=(Select Min(Case When Code = 'OHDATE' then DateChangedelse null end)From HREHWhere #MyTable.HRCo=HREH.HRCo and#MyTable.HRRef=HREH.HRRef ),TerminationDate=(select Max(Case When Type = 'N' thenDateChanged else null end)From HREHWhere #MyTable.HRCo=HREH.HRCo and#MyTable.HRRef=HREH.HRRef ),ReHireDate=(select MAX(Case When Code = 'HIRE' thenDateChanged else null end)From HREHWhere #MyTable.HRCo=HREH.HRCo and #MyTable.HRRef=HREH.HRRef )
View 2 Replies
View Related
Mar 11, 2008
Can anyone help me how to add a new column between a column in sql server 2005
i have did this one in SQL Server 2000 like below.
1. Add a new column using ALTER statement
2. EXEC sp_configure 'show advanced options',1
GO
RECONFIGURE
GO
EXEC sp_configure 'allow updates',1
GO
RECONFIGURE WITH OVERRIDE
GO
3.Change the colid in syscolumns table using UPDATE Statement
- But its not working in SQL Server 2005...it throws an adhoc error for system catalog table
View 5 Replies
View Related
May 28, 2015
I am trying to update a table and then also use OUTPUT clause to capture some of the columns. The code that I am using is something like the one below
UPDATE s
SET Exception_Ind = 1
OUTPUT s.Master_Id, s.TCK_NR
INTO #temp2
FROM Master_Summary s
INNER JOIN Exception d
ON d.Id = LEFT(s.Id, 8)
AND d.Barcode_Num = s.TCK_NR
WHERE s.Exception_Ind IS NULL
The above code is throwing an error as follows:
Msg 4104, Level 16, State 1, Procedure Process_Step3, Line 113
The multi-part identifier "s.Master_Id" could not be bound.
Msg 4104, Level 16, State 1, Procedure Process_Step3, Line 113
The multi-part identifier "s.TCK_NR" could not be bound.
View 5 Replies
View Related
Oct 6, 2014
I am trying to use a stored procedure to update a column in a sql table using the value from a variable table I getting errors because my syntax is not correct. I think table aliases are not allowed in UPDATE statements.
This is my statement:
UPDATE [dbo].[sessions_teams] stc
SET stc.[Talks] = fmt.found_talks_type
FROM @Find_Missing_Talks fmt
WHERE stc.sessionid IN (SELECT sessionid FROM @Find_Missing_Talks)
AND stc.coupleid IN (SELECT coupleid FROM @Find_Missing_Talks)
View 2 Replies
View Related
Oct 6, 2006
Hi
I can't figure out how to do this and hope you guys can give me a hint....
I want to select all columns from a table except one column:
For example,
A table has 20 columns : {1,2,3.....20}
To select all of columns in a table, i could use
select * from table;
However, I want to select only column {1....19}
I do not want to type the column names in one by one in the SQL query,
is there a way to achieve this in a short form of Select?
Thanks,
View 15 Replies
View Related
Apr 4, 2007
Hi,I have an Excel file with 400 rows of old values and the correspondingnew values. My table currently has 10 columns out of which 3 columnsuse the old value specified in the excel file. I need to update thoseold values in the columns with the new values from the Excel file.Please guide me as to how to proceed with this.Thanks in advance!
View 4 Replies
View Related
May 27, 2015
How can I pervert dropping the column in the table (probably some process doing that and I want to find it) ? I need to be able to modify but not alter / drop column .
View 4 Replies
View Related
Oct 31, 2014
‘Trying to SELECT INTO a new table all columns of a table based on a DISTINCT value of one column so for example:
SELECT *
INTO new_table
FROM old_name
WHERE old_table.column IS DISTINCT’
View 4 Replies
View Related
Sep 19, 2012
Need to update one table with value of a column in another table plus a constant:
UPDATE TABLE_A
SET TABLE_A.COLA=TABLE_B.COLB+'10'
FROM TABLE_A
INNER JOIN TABLE_B
ON TABLE_A.COLA=TABLE_B.COLA
WHERE TABLE_A.COLA=TABLE_B.COLA
The above statement works except the concatenated string has space between TABLE_B.COLB text and '10'. How to remove the space (4 characters) so that the string shows as one word 'TABLE_B.COLB10'?
View 2 Replies
View Related
Jul 8, 2014
I have to tables say 'employee1' and 'employee2'
employee1 has lastname
employee2 has firstname, lastname
i have to update firstname in employee1 from firstname in employee2 table and the common field for both tables is 'lastname'
View 8 Replies
View Related
Sep 2, 2005
Hi, I have two tables. I want to update two columns in my first table,[ADD_BSL_SALES] and [ADD_BSL_COST] with two values [Sales] and[Costs] held in my #temp table but based on a RUN_DATE from my firsttable.Can anyone point me in the right direction?Thanks in Advance ï?ŠBryanCREATE TABLE [GROSMARG_AUDIT_ADDITION] ([RUN_DATE] [datetime] NULL ,[SALES_DIFF] [numeric](19, 6) NULL ,[COST_DIFF] [numeric](19, 6) NULL ,[ADD_BSL_SALES] [numeric](18, 0) NULL ,[ADD_BSL_COST] [numeric](18, 0) NULL ,[ADD_SALES_DIFF] [numeric](18, 0) NULL ,[ADD_COST_DIFF] [numeric](18, 0) NULL) ON [PRIMARY]GOINSERT RUN_DATE,datetime,INSERT SALES_DIFF,numeric(19,6),INSERT COST_DIFF,numeric(19,6)INSERT ADD_BSL_SALES,numeric(18,0),INSERT ADD_BSL_COST,numeric(18,0),INSERT ADD_SALES_DIFF,numeric(18,0)INSERT ADD_COST_DIFF,numeric(18,0)--- Second TableCREATE TABLE #DUPTOTALS[Sales][Costs]
View 1 Replies
View Related
Jul 20, 2005
I need to update a table by copying a column from another table(having the samestructure, but on another database), from the record having the sameprimary key.1 - What is the correct query?2 - I tried copying them record by record, but the datatype is ntext,(it displays <longtext> in the result pane), and trying to update it results in thefollowing errormessage:The text, ntext, and image data types are invalid in this subquery oraggregateexpression.I tried variations of the following:UPDATE TABLESET column0 = (SELECTcolumn0FROManotherDB.dbo.TABLEWHEREanotherDB.dbo.TABLE.column1 = column1)WHEREanotherDB.dbo.TABLE.column1 = column1
View 1 Replies
View Related
Mar 25, 2008
hello all,
I don't know how to update table A with data from table B without specifying every column.
These two tables have the same fields and same structure.
I know that it's possible to do the following:
update table A
set A.name = B.name,
A.job = B.job
from table B
But I have many columns and don't want to describe every column, is that possible?
Thanks!
View 6 Replies
View Related
Sep 25, 2007
Is it possible to update from one table to another?Pls examine my code here:
UPDATE tStaffDir SET tStaffDir.ft_prevemp = ISNULL(tStaffDir_PrevEmp.PrevEmp01, ' ') + ' ' + ISNULL(tStaffDir_PrevEmp.PrevEmp02, ' ') + ' ' + ISNULL(tStaffDir_PrevEmp.PrevEmp03, ' ') + ' ' + ISNULL(tStaffDir_PrevEmp.PrevEmp04, ' ') + ' ' + ISNULL(tStaffDir_PrevEmp.PrevEmp05, ' ') Where tStaffDir_PrevEmp.ID=tStaffDir.ID
I am trying to concatenate the columns from tStaffDir_PrevEmp to tStaffDir but I have this error where tStaffDir_PrevEmp is recognised as a column and not a table.
Pls advise how this can be done. Many Thanks.
View 3 Replies
View Related
Jan 30, 2007
I have a table wherein I have to update a particular column (receipt code) based on another column of the same table (receipt number). i have to do calculations in order to generate the correct receipt code, and i have to do this on every row of the table. how can i do this? will this update be in a loop or something?
View 6 Replies
View Related
May 13, 2014
I need to write a update statement which will update the same table with value from the same column but the values will be changing.
For an example.
The source table is as below.
ROWID DATA Header
1 AAA H1
2 isa1
3 isb2
4 AAA3b3 H2
5 same
Now the records with rowid 2 and 3 should be updated with H1 as Header which is present in the Rowid 1.
Similarly the record rowid 5 should be updated with H2 as header from rowid 4.
View 5 Replies
View Related
Jan 2, 2014
I am trying to remove a user from Reporting Services via code. I have found that the way to do this is to remove their details from an XML field in the table SecData
The name of the column is xml_description
An example value of the column is below:
<Policy>
<GroupUserName>BUILTINAdministrators</GroupUserName>
<GroupUserId>AQIAAAAAAAUgAAAAIAIAAA==</GroupUserId>
<Roles>
<Role>
<Name>Content Manager</Name>
[Code]....
I would like to remove the bolded part in the column when I put in the user's name.
So the code would start with:
Declare @username varchar (20)
Set @ username = 'EMEAMJohnson'
Followed by the logic to remove the bolded part of the column.
The column is called xml_description and the name of the table is SecData.
View 17 Replies
View Related
Apr 26, 2007
Hello all, was wondering if you could point me in the right direction for this.
I have a db with a column classifications, and in that column are 'Accountants - (1234)' 'Book-keepers - (18) etc etc. Now what I want to do is remove the - (xxxx) section and obviously the white space, so I am just left with 'Accountants' 'Book-keepers' etc.
1. Is there an easy way to do this?
Ok so my thoughts were create a another table and put the ammended classifications in that to update the first table. Your probably asking why not just do it on the first table...Answer. There are over 150,000 records to change.
So I now have my first table with column classification and my second table with the correct classification ammendments.
I can sit down and manually type
UPDATE table1
SET classifications = 'Accountants'
Where classifications = 'Accounts - (xxxx)'
until i have completed the entire list in table 2 but I was hoping you good people would know a way to work through the list so it would automatically update each classification correctly.
The problem I have here is I dont know how to work through table 2 and match it to something in table 1 and update it.
Any help is greatfully appreciated
View 16 Replies
View Related
Apr 11, 2008
Hi,
I am quite new in SSIS and I have a question. I don't know what is the best way to get it work...
So simply I have in my SQL Server database 2 tables :
First table "SER" fields
SER_ID
SER_IS_CHANGE_RELATED
where I have only the field SER_ID filled like
SER_ID SER_IS_CHANGE_RELATED
1234 NULL
1235 NULL
1236 NULL
Second table "SRE" fields
SRE_ID
SRE_SER_ID
SRE_CHA_ID
and the content would be for example
SRE_ID SRE_SER_ID SRE_CHA_ID
1 1234 2345
2 1234 2346
3 1236 2347
The 2 tables are related by the fields : SER_ID = SRE_SER_ID
So I would like to have the following result in my table "SER":
SER_ID SER_IS_CHANGE_RELATED
1234 True
1235 NULL
1236 True
"True" because one or more entry is present in table "SRE" for each SER_ID (= SRE_SER_ID)
Hope my example is clear....
Thanks for your help
View 3 Replies
View Related
Aug 14, 2012
I have a table with a string value, where all values are seperated by a space/blank. I now want to use SQL to split all the values and insert them into a different table, which then later will result in deleting the old table, as soon as I got all values out from it.
Old Table:
Code:
ID, StringValue
New Table:
Code:
ID, Value1, Value2
Do note: Value1 is INT, Value2 is of nvarchar, hence Value2 can contain spaces... I just need to split on the FIRST space, then convert index[0] to int, and store index[1] as it is.
I can split on all spaces and just Select them all and add them like so: SELECT t.val1 + ' ' + t.val2... If I cant find the first space that is... I mean, first 2-10 characters in the string can be integer, but does not have to be.Shall probably do it in code instead of SQL?Now I want to run a query that selects the StringValue from OldTable, splits the string by ' ' (a blank) and then inserts them into New Table.
Code:
SELECT CASE CHARINDEX(' ', OldTable.stringvalue, 1)
WHEN 0 THEN OldTable.stringvalue
ELSE SUBSTRING(OldTable.stringvalue, 1, CHARINDEX(' ', OldTable.stringvalue, 1) - 1)
END
AS FirstWord
FROM OldTable
Found an example using strange things like CHARINDEX..But issue still remains, because the first word is of integer, or it does not have to be...If it isn't, there is not "first value", and the whole string shall be passed into "value2".How to detect if the very first character is of integer type?
Code:
@declare firstDigit int
IF ISNUMERIC(SUBSTRING(@postal,2,1) AS int) = 1
set @firstDigit = CAST(SUBSTRING(@postal,2,1) AS int)
ELSE
set @firstDigit = -1
[code]....
View 2 Replies
View Related
Feb 24, 2015
I have the following 2 Query's - case when Table has no Identity Column and other with identity Column . I am planning to make it to single Query .
Query 1:
SELECT @ColumnNamesWhenNoIdentity = COALESCE(@ColumnNamesWhenNoIdentity + ',', '') + Name +'= SOURCE.'+Name
FROM sys.columns WITH(NOLOCK) WHERE object_id =
(
SELECT sys.objects.object_id
FROM sys.objects WITH(NOLOCK)
INNER JOIN sys.schemas WITH(NOLOCK) ON sys.objects.schema_id = sys.schemas.schema_id
WHERE sys.objects.TYPE = 'U' AND sys.objects.Name = 'Testing1' AND sys.schemas.Name ='dbo'
)
Query2:
SELECT @ColumnNamesWhenNoIdentity = COALESCE(@ColumnNamesWhenNoIdentity + ',', '') + Name +'= SOURCE.'+Name
FROM sys.columns WITH(NOLOCK) WHERE is_identity != 1 AND object_id =
(SELECT sys.objects.object_id FROM sys.objects WITH(NOLOCK)
INNER JOIN sys.schemas WITH(NOLOCK) ON sys.objects.schema_id = sys.schemas.schema_id
WHERE sys.objects.TYPE = 'U' AND sys.objects.Name = 'Testing2' AND sys.schemas.Name ='dbo'
)
View 8 Replies
View Related
Jun 17, 2015
I have a SQL query like this
select CurrencyCode,TransactionCode,TransactionAmount,COUNT(TransactionCode) as [No. Of Trans] from TransactionDetails where CAST(CurrentTime as date)=CAST(GETDATE()as date) group by TransactionCode, CurrencyCode,TransactionAmount order by CurrencyCode
As per this query I got the result like this
CurrencyCode TransactionCode TransactionAmount No.OfTrans
AEDÂ Â Â BNTÂ Â Â 1Â Â Â 1
AEDÂ Â Â BNTÂ Â Â 12Â Â Â 1
AEDÂ Â Â SCNÂ Â Â 1Â Â Â 1
AEDÂ Â Â SNTÂ Â Â 1Â Â Â 3
[Code] ....
But I wish to grt result as
CurrencyCode TransactionCode TransactionAmount No.OfTrans
AEDÂ Â Â BNTÂ Â 13Â Â Â 2
AEDÂ Â Â SCNÂ Â Â 1Â Â Â 1
AEDÂ Â Â SNTÂ Â Â 11Â Â Â 7
AFNÂ Â Â BPCÂ Â Â 8Â Â Â 6
[Code] ....
I also tried this
select CurrencyCode,TransactionCode,TransactionAmount,COUNT(TransactionCode) as [No. Of Trans]
from TransactionDetails where CAST(CurrentTime as date)=CAST(GETDATE()as date)
group by TransactionCode order by CurrencyCode
But of course this codes gives an error, but how can I get my desired result??
View 5 Replies
View Related
Sep 6, 2007
How do I update a table's column, with the values of another tables column where the primary key between is Part_Number?
table2 = temp_table
Update Actuator_Components Set Scanned_Drawings = table2.Scanned_Drawings
View 2 Replies
View Related