Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 General SQL Server Forums
 New to SQL Server Programming
 update a table from another table

Author  Topic 

asm
Posting Yak Master

140 Posts

Posted - 2005-10-18 : 01:08:04
Hi
I have to update a gen table with a sum(amount) of txn table
now i have done this from froent end I want to done this with backend
how can i do this please help...

my vb code
----------
Private Sub UpdateGen()
Set cmdobj = New Command
Set Rtxn = New ADODB.Recordset
Set Rgen1 = New ADODB.Recordset
Dim opac As String
Dim opamt As Double
Rgen1.Open "gen", ConnectAcct, adOpenKeyset, adLockPessimistic, adCmdTable
With cmdobj
.ActiveConnection = ConnectAcct
.CommandText = "select glcode, sum(amount) as tamt from txn group by glcode order by glcode"
End With
Set Rtxn = cmdobj.Execute
If Not ((Rtxn.BOF = True) And (Rtxn.EOF = True)) Then
Rtxn.MoveFirst
Do While Not Rtxn.EOF
opac = Rtxn!Glcode
If IsNull(Rtxn!tamt) Then opamt = 0 Else opamt = Rtxn!tamt
Rgen1.MoveFirst
Do While Not Rgen1.EOF
If UCase(opac) = UCase(Rgen1!Glcode) Then
Rgen1!clbal = (Rgen1!amount + opamt)
Rgen1.Update
Exit Do
End If
Rgen1.MoveNext
Loop
Rtxn.MoveNext
Loop
End If
Rgen1.Requery
Rgen1.Close
Rtxn.Close
cmdobj.ActiveConnection = Nothing
Set Rgen1 = Nothing
Set Rtxn = Nothing
End Sub


thanks

asm



jen
Master Smack Fu Yak Hacker

4110 Posts

Posted - 2005-10-18 : 01:10:57
start with this...

quote:

Subqueries in UPDATE, DELETE, and INSERT Statements
Subqueries can be nested in UPDATE, DELETE, and INSERT statements, as well as in SELECT statements.

The following query doubles the price of all books published by New Moon Books. The query updates the titles table; its subquery references the publishers table.

UPDATE titles
SET price = price * 2
WHERE pub_id IN
(SELECT pub_id
FROM publishers
WHERE pub_name = 'New Moon Books')

Here's an equivalent UPDATE statement using a join:

UPDATE titles
SET price = price * 2
FROM titles INNER JOIN publishers ON titles.pub_id = publishers.pub_id
AND pub_name = 'New Moon Books'





HTH

--------------------
keeping it simple...
Go to Top of Page

asm
Posting Yak Master

140 Posts

Posted - 2005-10-19 : 00:37:59
Hi
I want to update gen table clbal with txn table sum of amount fileds group by glcode by this query i can update the same but the problem if their is no glcode in txn table but glcode in gen table and have a opening balance then clbal not update with opening balance it show null.


UPDATE gen
SET clbal = gen.amount + gcl.tamt
FROM (select top 100 percent glcode, (case when sum(txn.amount)=' ' or sum(txn.amount) is null then 0 else sum(txn.amount) end) as tamt from txn group by glcode order by glcode) as gcl WHERE gen.glcode = gcl.glcode


pls guide how to done this...

thanks

asm
Go to Top of Page

madhivanan
Premature Yak Congratulator

22864 Posts

Posted - 2005-10-19 : 00:50:57
Before trying this take a backup of Gen table and if the updation is wrong restore it

Update G
set clbal=amount+gcl.amt from Gen
inner join
(select top 100 percent glcode, (case when sum(txn.amount)=' ' or
sum(txn.amount) is null then 0 else sum(txn.amount) end) as tamt from txn group by
glcode order by glcode) as gcl
on G.glcode = gcl.glcode


Madhivanan

Failing to plan is Planning to fail
Go to Top of Page

jen
Master Smack Fu Yak Hacker

4110 Posts

Posted - 2005-10-19 : 00:56:40
better do a select first before updating to test the query,
always better than restoring

just a tip
quote:
Originally posted by madhivanan

Before trying this take a backup of Gen table and if the updation is wrong restore it

Update G
set clbal=amount+gcl.amt from Gen
inner join
(select top 100 percent glcode, (case when sum(txn.amount)=' ' or
sum(txn.amount) is null then 0 else sum(txn.amount) end) as tamt from txn group by
glcode order by glcode) as gcl
on G.glcode = gcl.glcode


Madhivanan

Failing to plan is Planning to fail



--------------------
keeping it simple...
Go to Top of Page

madhivanan
Premature Yak Congratulator

22864 Posts

Posted - 2005-10-19 : 01:06:56
Good

I think this is also Good

Begin Transaction
Update Query
Select Query -- To check whether the updation is correct
If correct Commit Transaction
else Rollback Transaction

Madhivanan

Failing to plan is Planning to fail
Go to Top of Page

asm
Posting Yak Master

140 Posts

Posted - 2005-10-19 : 06:49:25
Still the problem remains...

asm
Go to Top of Page

madhivanan
Premature Yak Congratulator

22864 Posts

Posted - 2005-10-19 : 07:40:37
Did you get error?

Madhivanan

Failing to plan is Planning to fail
Go to Top of Page

asm
Posting Yak Master

140 Posts

Posted - 2005-10-21 : 02:38:22
No Error message but desire result not come...

Go to Top of Page

madhivanan
Premature Yak Congratulator

22864 Posts

Posted - 2005-10-21 : 02:49:44
Post some sample data and the result you want

Madhivanan

Failing to plan is Planning to fail
Go to Top of Page

asm
Posting Yak Master

140 Posts

Posted - 2005-10-21 : 07:58:45
gen table :
code opbal
c1 500
c2 700
c3 100
c4 50

txn table
code amount
c1 50
c3 25
c4 500

result will be in gen table
code opbal clbal
c1 500 450
c2 700
c3 100 0
c4 50 -450

i want c2 should update with 700 instead of null


asm
Go to Top of Page

madhivanan
Premature Yak Congratulator

22864 Posts

Posted - 2005-10-21 : 09:11:09
Instead of inner join use Left Join. That will work correctly

Madhivanan

Failing to plan is Planning to fail
Go to Top of Page

asm
Posting Yak Master

140 Posts

Posted - 2005-10-22 : 01:04:47
thanks.. for guiding
query has been solved :

Update Gen
set gen.clbal=gen.amount+(case when gcl.tamt=' ' or gcl.tamt is null then 0 else gcl.tamt end) from Gen
left join
(select top 100 percent glcode, sum(txn.amount)as tamt from txn group by
glcode order by glcode) as gcl
on Gen.glcode = gcl.glcode


asm
Go to Top of Page

madhivanan
Premature Yak Congratulator

22864 Posts

Posted - 2005-10-22 : 01:10:38
Glad to know my query helped you

Madhivanan

Failing to plan is Planning to fail
Go to Top of Page

Kristen
Test

22859 Posts

Posted - 2005-10-22 : 06:17:21
"better do a select first before updating to test the query"

I'm sure this is obvious, but here's what I do:

So I want to do

UPDATE MyTable
SET ColA = 'FOO'
WHERE ColB = 'BAR'

what I write is

UPDATE U
SET
ColA = 'FOO'
FROM MyTable AS U
WHERE ColB = 'BAR'

which I actually write like this:

-- UPDATE U
SET
-- SELECT ColB, ColC, ColA AS [ColA_ORIGINAL],
ColA = 'FOO'
-- SELECT *
FROM MyTable AS U
WHERE ColB = 'BAR'

1) the UPDATE is commented out, so I cannot run it "accidentally"
2) I put in one or other of the SELECT statements - depends on whether I actually want to see what the calculated column is going to look like (top one), or just some of the data in the original table (bottom one)

I then highlight, in Query Analyser, from the BOTTOM upwards to include just to the start of the SELECT, and execute it. If that's OK I extend the highlight upwards (cursor is already at the top, just press Shift+Up/Left arrow) until the UPDATE is highlighted and then execute that.

For additional safety I may also include a

-- SELECT * INTO TEMP_MyTable_20051022 FROM MyTable

which I can execute to pre-copy the original data into a temporary table. I always prefix the table name with "TEMP" so that all such "just in case" tables are grouped alphabetically, and put today's date on the end of the name - then when I'm having a cleanup I know how "old" the data is, and can get rid of it after a reasonable period.

Also, on production databases I always insert into another database - no sense clogging up the MDF file with temporary stuff! So actually it would be:

-- SELECT * INTO MyTempDB.dbo.TEMP_MyTable_20051022 FROM MyTable

Of course I may decide that all that is still "risky" so I then want a TRANSACTION block, so I do

BEGIN TRANSACTION
UPDATE U
SET
-- SELECT ColB, ColC, ColA AS [ColA_ORIGINAL],
ColA = 'FOO'
-- SELECT *
FROM MyTable AS U
WHERE ColB = 'BAR'
--
ROLLBACK
-- COMMIT


The idea here is that if I run it, by accident, it will rollback. I have to explicitly highlight from BEGIN TRANSACTION down to, but not including, ROLLBACK - run that, and if its OK then highlight the COMMIT and run it, otherwise use the ROLLBACK.

NOTE: If there are a bunch of statements in the block with "GO" between then I never highlight past more than one GO at a time. I work thought them highlighting one at a time, and once I've got to the last GO I use the COMMIT statement if I'm happy, otherwise if any of the individual blocks give error, or an unexpected number of rows, etc., then I use the ROLLBACK instead. Here's an example:

CREATE TABLE TEST051022
(
MyPK varchar(10) NOT NULL,
MyData varchar(50) NOT NULL,
PRIMARY KEY
(
MyPK
)
)
GO
PRINT 'Insert initial 1'
GO
INSERT INTO TEST051022 VALUES (10, 'Ten (Original)')
GO

-- OK, We have "some" data in the table
-- Now we will generate an error, and then insert an extra row

PRINT 'Begin Trans'
GO
BEGIN TRANSACTION
GO

-- This will cause error and will rollback the transaction!
PRINT 'Re-create duplicate table'
GO
CREATE TABLE TEST051022
(
MyPK varchar(10) NOT NULL,
MyData varchar(50) NOT NULL,
PRIMARY KEY
(
MyPK
)
)
GO

-- This will succeed
-- NOTE The transaction is now "dead" so this is OUTSIDE the transaction block!
PRINT 'Insert 20'
GO
INSERT INTO TEST051022 VALUES (20, 'Twenty')
GO

-- This rollback will fail!
PRINT 'Rollback'
GO
ROLLBACK
GO

PRINT 'Rows in the table are:'
GO
SELECT * FROM TEST051022
GO
DROP TABLE TEST051022
GO

and the results are (Note that the "20" insert succeeded and the ROLLBACK failed

Insert initial 1

(1 row(s) affected)

Begin Trans
Re-create duplicate table
Server: Msg 2714, Level 16, State 6, Line 1
There is already an object named 'TEST051022' in the database.

Insert 20

(1 row(s) affected)

Rollback
Server: Msg 3903, Level 16, State 1, Line 1
The ROLLBACK TRANSACTION request has no corresponding BEGIN TRANSACTION.

Rows in the table are:
MyPK MyData
---------- --------------------------------------------------
10 Ten (Original)
20 Twenty

(2 row(s) affected)

Kristen
Go to Top of Page

madhivanan
Premature Yak Congratulator

22864 Posts

Posted - 2005-10-22 : 06:33:38
Good Stuff Kris. Your explanation is much appreciated

Madhivanan

Failing to plan is Planning to fail
Go to Top of Page
   

- Advertisement -