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
 SQL Server 2008 Forums
 Transact-SQL (2008)
 insert qry with a value from another tbl

Author  Topic 

svibuk
Yak Posting Veteran

62 Posts

Posted - 2012-10-11 : 05:46:52
i have a below qry

IF EXISTS (SELECT * FROM trans WHERE cid =36 and pid=37)
UPDATE trans set pid='37' WHERE cid =36 and pid=37
Else
insert into trans (tid,cid,pid,qty,rate,frmdt,todt)
values (207,36, 37,0,55 ,'1/1/1900','1/1/1900')



here currently when inserting i need to get the rate value from another table

select prate from M_PRDT where PID=37
this rate value needs to be put in place of 55
how can it be done in a single stmt without having to use another qry & execute it and get the records

malpashaa
Constraint Violating Yak Guru

264 Posts

Posted - 2012-10-11 : 06:10:04
Try this:

...
insert into trans(tid, cid, pid, qty, rate, frmdt, todt)
select 207, 36, 37, 0, prate, '1/1/1900', '1/1/1900'
from M_PRDT where PID=37




For us, there is only the trying. The rest is not our business. ~T.S. Eliot

Muhammad Al Pasha
Go to Top of Page

svibuk
Yak Posting Veteran

62 Posts

Posted - 2012-10-11 : 08:34:08
thankls
tht works but there is slight prblm in this which i had not noticed

1) how do i update the rate in update stmt given above rate= ??
2)suppose the rsate of a product X till last month was 100 but the rate was updated in the master product table from current month
so when above stmt is executed fr current month then the rate of product X shld not be update fr any previous months
it shld be updated frm current month only

my trans tbl has fields
tid cid pid qty rate month Year AMOUNT Billno frmdt todt

Go to Top of Page

visakh16
Very Important crosS Applying yaK Herder

52326 Posts

Posted - 2012-10-11 : 15:53:33
quote:
Originally posted by svibuk

thankls
tht works but there is slight prblm in this which i had not noticed

1) how do i update the rate in update stmt given above rate= ??
2)suppose the rsate of a product X till last month was 100 but the rate was updated in the master product table from current month
so when above stmt is executed fr current month then the rate of product X shld not be update fr any previous months
it shld be updated frm current month only

my trans tbl has fields
tid cid pid qty rate month Year AMOUNT Billno frmdt todt




1. it would require a join to rate table as below
UPDATE t
set t.pid='37' ,t.rate = m.prate
FROM trans t
INNER JOIN M_PRDT m
ON m.PID = t.pid
WHERE t.cid =36 and t.pid=37

2. for this do you've a date field in yout M-PRDT table to indicate range for which a rate is valid?

------------------------------------------------------------------------------------------------------
SQL Server MVP
http://visakhm.blogspot.com/

Go to Top of Page
   

- Advertisement -