日期:2014-05-18 浏览次数:20462 次
CREATE TABLE TABLE1 ( QU1 VARCHAR(100), STDT VARCHAR(100), SUDT VARCHAR(100), SFDT VARCHAR(100), UFDT VARCHAR(100) ) CREATE TABLE TABLE2 ( QU1 VARCHAR(100), FEL1 VARCHAR(100), FEL2 VARCHAR(100) ) GO INSERT INTO TABLE1 SELECT '3-SA','20120101','20120504','20120708','20120910' UNION ALL SELECT '1-HA','20121010','20120401','20120727','20120501' UNION ALL SELECT '2-TD','20121001','20120602','20121231','20120512' UNION ALL SELECT '3-HA','20121101','20120805','20120110','20120807' INSERT INTO TABLE2 SELECT '3-SA','SUDT','UFDT' UNION ALL SELECT '1-HA','STDT','SUDT' UNION ALL SELECT '2-TD','SUDT','SFDT' UNION ALL SELECT '3-HA','SFDT','STDT' SELECT * FROM TABLE1 SELECT * FROM TABLE2 GO CREATE TABLE #TAB(P1 VARCHAR(100),P2 VARCHAR(100),P3 VARCHAR(100),P4 VARCHAR(100),P5 VARCHAR(100)) DECLARE @SQL VARCHAR(8000),@P1 VARCHAR(100),@P2 VARCHAR(100),@P3 VARCHAR(100) EXEC (@SQL) DECLARE CUR_SOR CURSOR FOR SELECT * FROM TABLE2 OPEN CUR_SOR FETCH NEXT FROM CUR_SOR INTO @P1,@P2,@P3 WHILE @@FETCH_STATUS=0 BEGIN SET @SQL = 'INSERT INTO #TAB ' + ' SELECT '''+@P1+''' ,''' + @P2 + ''',''' + @P3+''','+ @P2+',' + @P3 +' FROM TABLE1 WHERE QU1='''+@P1+''' ' EXEC (@SQL) FETCH NEXT FROM CUR_SOR INTO @P1,@P2,@P3 END CLOSE CUR_SOR DEALLOCATE CUR_SOR SELECT * FROM #TAB DROP TABLE #TAB GO DROP TABLE TABLE1 DROP TABLE TABLE2