drop table #SMS go create table #SMS ( dbname varchar(100), compId BIGINT, userName VARCHAR(100), PW VARCHAR(1000) ) SELECT * FROM #SMS INSERT #SMS SELECT db_name() ,1,UserName,Password FROM( SELECT (SELECT FValue FROM TSystemParam WHERE FKey = 'SMSUserName' AND FValue != '') AS UserName, (SELECT FValue FROM TSystemParam WHERE FKey = 'SMSPASSWORD' AND FValue != '' ) AS Password ) AS T WHERE UserName IS NOT NULL INSERT #SMS SELECT db_name() ,TU.FCompId,UserName,Password FROM (SELECT FCompId, FValue AS UserName FROM TSystemParamSub WHERE FParamKey = 'SMSUserName' AND FValue != '') AS TU, (SELECT FCompId, FValue AS Password FROM TSystemParamSub WHERE FParamKey = 'SMSPASSWORD' AND FValue != '' ) AS TP WHERE TU.FCompID = TP.FCompId