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)
 How to display what MERGE will do?

Author  Topic 

Sqlraider
Yak Posting Veteran

65 Posts

Posted - 2011-08-12 : 13:38:45
I want to display the columns the MERGE statement below will
create for the UPDATE & INSERT portion. In other words I want to see what it is about to update/insert.
I tried using the Print function but keep getting syntax errors.

Code:

DECLARE @PrintMessage nvarchar(500);
MERGE STUDENTPROGRAMS AS sp
USING
(Select sd.ChildID, sd.SchoolID, sd.SchoolYear, sd.Mobility,
sd.DateIn, sd.DateOut,
sd.DateOfEntry, sd.UserOfEntry, sd.DateOfChange, sd.UserOfChange
,st.TermStartDate,
,s2.TermEndDate AS YREndDate
from StandardChildDemographics AS sd
left join SchoolTerms AS st
on sd.SchoolID = st.SchoolID
and sd.SchoolYear = st.SchoolYear
and st.TermNbr = 1
left join SchoolTerms AS s2
on sd.SchoolID = s2.SchoolID
and sd.SchoolYear = s2.SchoolYear
and s2.TermNbr = 4
where sd.DateOfChange >= dateadd(day,datediff(day,0,getdate())-20,0)
and sd.SchoolYear = '2010-2011'
and sd.Mobility = 'Y'
) AS i
ON sp.SchoolYR = i.SchoolYear
and sp.SID = i.ChildID
and ((sp.ProgStrt_DT = i.TermStartDate) OR (sp.ProgStrt_DT = i.DateIn))
WHEN MATCHED
THEN
-- this is where I want to see all columns
-- from both the row being updated & what the
-- columns are going to be updated with.
-- bascally display the columns here
UPDATE Set @PrintMessage = N'Update '
+ i.SchoolYear + N' ' + (CAST(i.ChildID as nvarchar(11))
+ (CAST(sp.ProgStrt_DT as char(11)));

;


OR is there a better way to see what is going to be executed?

Thanks.

sunitabeck
Master Smack Fu Yak Hacker

5155 Posts

Posted - 2011-08-12 : 13:55:50
If there are only a few rows, you could use the output clause to see what it will do and do a rollback. What I am thinking is something like this:

BEGIN TRAN
-- insert the code you posted here
OUTPUT
$action,
INSERTED.*,
DELETED.*;
ROLLBACK TRAN

You may not want to do this if you have hundreds or thousands of rows because the update/insert and the rollback may take forever.
Go to Top of Page

Sqlraider
Yak Posting Veteran

65 Posts

Posted - 2011-08-12 : 14:12:12
Just what I needed.

Thank You.
Go to Top of Page
   

- Advertisement -