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 using subquery

Author  Topic 

pginther
Starting Member

2 Posts

Posted - 2011-05-11 : 16:22:25
Hey all. Fairly new to writing T-SQL and I've hit a wall on something that I'm sure is fairly common. I have a table in one database that I need to update with values from another database. I have written the query that provides me with the information I need from database B, but can't figure out how to write the update statement to get it into database A.

Here is the script that gets me the info from database B:

Select t.loginid as AgentID, Count(c.CallID) as Opened, c.recvddate as Date
From Tracker as t
Inner Join CallLog as c
on t.loginid = c.recvdby
Where t.SecGroup in ('GroupA','GroupB')
and c.recvddate = CAST(DATEPART(year, GETDATE()) AS char(4))
+ '-' + RIGHT('00' + CAST(DATEPART(month, GETDATE()) AS
varchar(2)), 2) + '-' + RIGHT('00' + CAST(DATEPART(day,
GETDATE()) AS varchar(2)), 2) (I know this is rather crazy but the source date format is text, not DATETIME so I have to convert.)
Group by t.loginid, c.recvddate

I need to match the records in database A & B by the AgentID and Date fields. Based on that match, I want to insert the result in the "Opened" column of this query to the "Opened" column in database A.

Can anyone help me out? Thanks for helping out a (hopefully not for long) ignorant SQL dude

Thanks!
PG

sunitabeck
Master Smack Fu Yak Hacker

5155 Posts

Posted - 2011-05-11 : 20:46:18
You can modify your code as shown in red below:

with cte as
(

Select t.loginid as AgentID, Count(c.CallID) as Opened, c.recvddate as Date
From Tracker as t
Inner Join CallLog as c
on t.loginid = c.recvdby
Where t.SecGroup in ('GroupA','GroupB')
and c.recvddate = CAST(DATEPART(year, GETDATE()) AS char(4))
+ '-' + RIGHT('00' + CAST(DATEPART(month, GETDATE()) AS
varchar(2)), 2) + '-' + RIGHT('00' + CAST(DATEPART(day,
GETDATE()) AS varchar(2)), 2) (I know this is rather crazy but the source date format is text, not DATETIME so I have to convert.)
Group by t.loginid, c.recvddate

)
UPDATE a SET
Opened = b.Opened
FROM
DatabaseA.dbo.TableA a
INNER JOIN CTE b ON a.AgentId = b.AgentId AND a.Date = b.Date;
I obviously don't have your tables and data, so I have not tested the code. So before you do anything for real, please test.
Go to Top of Page

pginther
Starting Member

2 Posts

Posted - 2011-05-12 : 09:08:56
Thank you! I'll give it a shot and see what I get.

Thanks!
PG
Go to Top of Page
   

- Advertisement -