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 for table question

Author  Topic 

mrtweaver
Yak Posting Veteran

67 Posts

Posted - 2009-01-14 : 19:16:54
I have two tables, table1 and table2.

Table1 has numbers 1 to 99 for each of 3 conditions. So you have 1 to 99 with condition 1, 1 to 99 for condition 2 and 1 to 99 for condition 3.

Table2 just has the number 1 to 99

Both tables have the same column headings with the exception that table1 has an addition field called sel_on

What I am trying to do is copy the rows and columns from table1 into table2 where sel_on is a 1. If sel_on is a 0 (zero) I dont want to copy that row.

So lets say the query is run with condition1 and the sel_on is on only for the odd numbers. So row1 conditon1 from table1 would copy over to row1 of table2. Row2 condition1 is not on so it would not copy that row and it would not affect the data in that row on table2.

Here is what I have so far but it seems to copy all the rows and columns and does not seem to be affected by the sel_on.

update table2 set op = (select x.op from table1 where x.num=table2.num and table1.sel_on=1)

I know it has to be something simple but it is eluding me at this time. Thanks and have a great day.

Oh and I did try putting that table1.sel_on statement outside the parenthesis but when I did that it said it could not be bound.

tkizer
Almighty SQL Goddess

38200 Posts

Posted - 2009-01-14 : 19:18:28
update t2
set op = t1.op
from table2 t2
inner join table1 t1
on t2.num = t1.num
where t1.sel_on = 1

This is just an update statement, so if you want to copy rows, then you'll need an insert statement. Let us know how the above goes.

Tara Kizer
Microsoft MVP for Windows Server System - SQL Server
http://weblogs.sqlteam.com/tarad/

Subscribe to my blog
Go to Top of Page

tkizer
Almighty SQL Goddess

38200 Posts

Posted - 2009-01-14 : 19:20:45
Here's an example insert:

INSERT INTO Table2 (Column1, Column2, ...)
SELECT Column1, Column2, ...
FROM Table1
WHERE sel_on = 1

You may need to use a NOT EXISTS if Table2 already has data.

Tara Kizer
Microsoft MVP for Windows Server System - SQL Server
http://weblogs.sqlteam.com/tarad/

Subscribe to my blog
Go to Top of Page
   

- Advertisement -