Wednesday, March 5, 2008

generate insert stmt for mismatching tables

rem - struc_no_match_tbl is a table that has list of tables whose structure does not match
DECLARE @TBLNM VARCHAR(50)
DECLARE C2 CURSOR FOR
SELECT RECNAME FROM _NO_MATCH_TBL
OPEN C2
FETCH NEXT FROM C2 INTO @TBLNM
WHILE @@FETCH_STATUS = 0
BEGIN
DECLARE @FN VARCHAR(30),@CL VARCHAR(8000),@SL VARCHAR(8000),@CNTR INT ,@FT INT

Declare C1 CURSOR for SELECT FIELDNAME FROM PSRECFIELDALL WHERE RECNAME = @TBLNM
OPEN C1
FETCH NEXT FROM C1 INTO @FN
SELECT @CL = ' '
SELECT @SL = ' '
WHILE @@FETCH_STATUS = 0
BEGIN
SELECT @CNTR = COUNT(*) FROM sourcedatabase..PSRECFIELDALL WHERE RECNAME = @TBLNM AND FIELDNAME = @FN;
SELECT @FT = FIELDTYPE FROM PSDBFIELD WHERE FIELDNAME = @FN
SELECT @CL = @CL + @FN +',';
IF (@CNTR<>1)
IF @FT <> 2
SELECT @SL =@SL + ''' '''+','
ELSE
SELECT @SL = @SL +CHAR(0)+','
else
SELECT @SL = @SL + @FN + ',';
FETCH NEXT FROM C1 INTO @FN
END;
SELECT @CL =SUBSTRING(@CL,1,LEN(@CL)-1)
SELECT @SL =SUBSTRING(@SL,1,LEN(@SL)-1)


PRINT 'INSERT INTO PS_'+@TBLNM +'('+@CL+')'+'SELECT '+ @SL +' FROM '+'UCP83..PS_'+@TBLNM

CLOSE C1
DEALLOCATE C1

FETCH NEXT FROM C2 INTO @TBLNM
END;

CLOSE C2
DEALLOCATE C2

No comments: