Link to home
Start Free TrialLog in
Avatar of ScuzzyJo
ScuzzyJoFlag for United Kingdom of Great Britain and Northern Ireland

asked on

Using a join in dynamic sql

Hi

Every time I think that I might be starting to understand this, it seems to put me in my place!

I have the following code:

SET @maxcounter = 0;
--
WHILE @maxcounter < @maxcnt
BEGIN
    SET @crtcnt = @maxcounter + 1;
      SET @sqlstr = 'UPDATE A SET old_SSN' + CAST(@crtcnt AS VARCHAR) + ' = B.old_SSN' + CAST(@crtcnt AS VARCHAR) + 'FROM LFRD_Summary A LEFT OUTER JOIN LFRD B ON A.SSN = B.SSN';
      EXEC (@sqlstr);
    SET @maxcounter = @maxcounter + 1;
END

I get an error which doesn't refer to any of these lines but it ran fine before I put these in.

I have varying numbers of columns for old_ssn in both LFRD and LFRD_Summary.  I used SELECT DISTINCT to get the unique SSNs into LFRD_Summary from LFRD.  Now, I need to get the other column data into LFRD_Summary.

I've tried putting a join together using dynamic SQL to do this, using what I've learned on here, but it doesn't seem to like it.

The variables are declared elsewhere.

Can anybody help me please?

Thanks
Sarah
ASKER CERTIFIED SOLUTION
Avatar of Ryan Chong
Ryan Chong
Flag of Singapore image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of ScuzzyJo

ASKER

Hi Ryan

Thanks.  I think that works.

It's heartening as maybe I do understand it a bit now if I only left a space out!

Thanks
Sarah
It should become clearer within a year or two. :-) To actually understand it might take a bit longer.

Some basic questions:
What's the error message? (I don't see a space in front of FROM)
How big are the tables?
How often do you need to do this? Once?

The reason I ask the last two questions is that ordinarily I wouldn't use a WHILE loop (if I HAVE to loop, I usually use a well-configured cursor), but if it's a one-time thing or the amount of data is small then perhaps any old solution will do. Dealing with denormalized fields of this sort can be messy and possibly not worth the effort to do it 'right.'