Solved

Append a table from the rows returned by a SQL Statement

Posted on 2013-11-01
6
302 Views
Last Modified: 2013-11-08
A SQL statement returns rows and columns.  This works well.

I need to append a table from the returned rows.

Currently I am using SQLDataReader to read column values into a dataset.
Then I am parsing the dataset one row at a time and building an array.

Then I am parsing the array one row at a time and appending the values to a table.

What do I need to do to Append a table from the rows returned by a SQL Statement.
The appended table can be a table that has been cleared. Then all rows might be appended in a single statement instead of building and parsing a dataset.  

//SQL statement returns rows and columns.
  SqlCommand cmdShowGrid = new SqlCommand("usp_getExceptions", conStockSelect);
            cmdShowGrid.Connection = conStockSelect;
            cmdShowGrid.CommandType = System.Data.CommandType.StoredProcedure;
            cmdShowGrid.CommandTimeout = 1200;
            cmdShowGrid.CommandText = "usp_getExceptions";
            cmdShowGrid.Parameters.Clear();
            // cmdShowGrid.Parameters.AddWithValue("@MarketID", SqlDbType.Int).Value = 2;
            cmdShowGrid.Parameters.AddWithValue("@CurrFromDate", SqlDbType.Date).Value = dteSampleBCStart;
            cmdShowGrid.Parameters.AddWithValue("@CurrToDate", SqlDbType.Date).Value = dteSampleABStart;
            cmdShowGrid.Parameters.AddWithValue("@PrevFromDate", SqlDbType.Date).Value = dteSampleABEnd;
            cmdShowGrid.Parameters.AddWithValue("@PrevToDate", SqlDbType.Date).Value = dteSampleBCEnd;
            cmdShowGrid.Parameters.AddWithValue("@Min5DayAvg", SqlDbType.Decimal).Value = 1.00;
            cmdShowGrid.Parameters.AddWithValue("@Max5DayAvg", SqlDbType.Decimal).Value = 100.00;
            cmdShowGrid.Parameters.AddWithValue("@Curr5Prev8Min", SqlDbType.Decimal).Value = 1.05;
            cmdShowGrid.Parameters.AddWithValue("@Curr5Prev8Max", SqlDbType.Decimal).Value = lstMaxCurr5Prev8.SelectedValue; //Decimal.Add(decIncreases, decIncreasesPlus);
 
//using SQLDataReader to read column values into a dataset.
          SqlDataAdapter adpExceptions = new SqlDataAdapter(cmdShowGrid);
            DataSet dstExceptions = new DataSet();
            adpExceptions.Fill(dstExceptions, "Exceptions");

            SqlDataReader rdrStockHist;

            rdrStockHist = cmdShowGrid.ExecuteReader();

            double[,] dblArrException = new double[2000, 8];  // Numerical parameter values
            string[,] strArrException = new string[2000, 2];  // String parameter values

//Parsing the dataset one row at a time and building an array.
          if (rdrStockHist.HasRows)   // Build the array
            {
                while (rdrStockHist.Read())
                {
                    // Read the col values into arrays
                    dblArrException[intRow, 0] = Convert.ToDouble(rdrStockHist["SymbolID"]);
                    dblArrException[intRow, 1] = Convert.ToDouble(rdrStockHist["Curr5DayAvg"]);
                    dblArrException[intRow, 2] = Convert.ToDouble(rdrStockHist["Prev8DayAvg"]);
                    //dblArrException[intRow, 3] = Convert.ToDouble(rdrStockHist["PctChg"]);
                    //dblArrException[intRow,4]  = Convert.ToDouble(rdrStockHist["MarketID"]);
                    //dblArrException[intRow, 5] = 0;  Convert.ToDouble(rdrStockHist["PctUp"]);

                    //strArrException[intRow,0]  = rdrStockHist["SymbolName"].ToString();
                    //strArrException[intRow,1]  = rdrStockHist["SiteURL"].ToString();

                    intRow++;
                }
            }  // End (rdrSymbols.Read())

            rdrStockHist.Close(); // closing SqlDataReader

//Parsing the array one row at a time and appending the values to a table.

                SqlCommand cmdapdExceptions = new SqlCommand("usp_apdExceptions", conStockSelect);
                cmdapdExceptions.CommandType = System.Data.CommandType.StoredProcedure;
                cmdapdExceptions.CommandTimeout = 1200;

                for (int i = 0; i < intRow; i++)
                {
                    cmdapdExceptions.Parameters.Clear();
                    cmdapdExceptions.Parameters.Add("@SymbolID", SqlDbType.Int).Value = dblArrException[i, 0];
                    cmdapdExceptions.Parameters.Add("@Curr5DayAvg", SqlDbType.Float).Value = dblArrException[i, 1];
                    cmdapdExceptions.Parameters.Add("@Prev8DayAvg", SqlDbType.Float).Value = dblArrException[i, 2];


                    RunProcedure(cmdapdExceptions, "usp_apdExceptions");
                }  // End  for (int i = 0; i < intRow; i++)

                cmdapdExceptions.Dispose();
0
Comment
Question by:Dovberman
  • 3
  • 2
6 Comments
 
LVL 40

Accepted Solution

by:
Sharath earned 250 total points
ID: 39616924
Do you have both the tables on same server? You can append the rows with one INSERT statement like

INSERT TableB
SELECT * FROM TableA
0
 
LVL 15

Assisted Solution

by:gplana
gplana earned 250 total points
ID: 39616926
If you just want to insert values from a SELECT into your table, you should just make a INSERT SELECT:

INSERT INTO your_table (field1, field2, ..., fieldN) SELECT field1, field2, ...., field N FROM another_table....)

Just understand that the fields of the SELECT should be of the same datatype of the field lisf of the INSERT.

Hope it helps.
0
 

Author Comment

by:Dovberman
ID: 39618028
Yes, both tables are on the same server, and datatypes match.

Thanks

I will try this and give feedback tomorrow.


INSERT INTO TargetTableName (field1, field2, ..., fieldN)
SELECT  
 w.UserName
, w.SymbolID
, @FromDate AS FromDate
, @ToDate AS ToDate
, (SELECT SymbolName FROM Symbol WHERE SymbolID = w.SymbolID) AS SymbolName
, (SELECT SUBSTRING(SecName, 1, 20) FROM Symbol WHERE SymbolID = w.SymbolID) AS SecName
, w.MarketID
, (SELECT MarketName FROM Market
      WHERE MarketID = w.MarketID)
      AS MarketName
, w.WatchListID
, w.PickDate
, @ResearchSiteURL AS SiteURL

, @SiteEvalType AS SiteEvalType      

, (SELECT Count(*) FROM DownLoadDates
  WHERE QuoteDate >=(w.PickDate +1 ) AND MarketID = 1) As DaysOnList

, (SELECT PickDatePrice FROM WatchList
      WHERE PickDate=w.PickDate    
      AND SymbolID=w.SymbolID)
      AS PickPrice    

,  (SELECT ClosePrice FROM StockHist
      WHERE QuoteDate=@FromDate  
      AND SymbolID=w.SymbolID)
      AS BasePrice

,  (SELECT COUNT(*) FROM StockHist
      WHERE ClosePrice > ClosePricePrev
      AND QuoteDate BETWEEN w.PickDate AND @AsOfDate  
      AND  SymbolID=w.SymbolID )
      AS PriceUpCount
     
      --Pricechange
     
  , (SELECT Top(1) ClosePrice FROM StockHist
      WHERE QuoteDate=@AsOfDate    
      AND SymbolID=w.SymbolID)
      -
       (SELECT ClosePrice FROM StockHist
      WHERE QuoteDate=@FromDate  
      AND SymbolID=w.SymbolID)
      AS PriceChange
     
 ,  (SELECT Top(1) ClosePrice FROM StockHist
      WHERE QuoteDate=@AsOfDate    
      AND SymbolID=w.SymbolID)
      AS CurrentPrice
     
 , (SELECT 2* STDEV(HighPrice-LowPrice)
      FROM StockHist WHERE SymbolID=w.SymbolID)
      AS CI95
 
  -- PctChange = ((CurrentPrice - BasePrice)/BasePrice) * 100
 
  -- Fix -- PctChange = ((CurrentPrice - PickPrice)/PickPrice) * 100
     
   ,( ( (SELECT Top(1) ClosePrice FROM StockHist
      WHERE QuoteDate=@AsOfDate    
      AND SymbolID=w.SymbolID)
     
      -
       (SELECT ClosePrice FROM StockHist
      WHERE QuoteDate=@FromDate  
      AND SymbolID=w.SymbolID) )
     
      /
     
         (SELECT ClosePrice FROM StockHist
      WHERE QuoteDate=@FromDate  
      AND SymbolID=w.SymbolID) ) * 100
     
      AS PctChange
     
FROM Watchlist w
WHERE w.UserID='0A742A71-B5D5-4E00-9E5F-BD3C82B5936A'
0
PRTG Network Monitor: Intuitive Network Monitoring

Network Monitoring is essential to ensure that computer systems and network devices are running. Use PRTG to monitor LANs, servers, websites, applications and devices, bandwidth, virtual environments, remote systems, IoT, and many more. PRTG is easy to set up & use.

 
LVL 40

Expert Comment

by:Sharath
ID: 39618051
I think your INSERT query can  be optimized. The StockHist table is queried many times. let me know.
0
 

Author Comment

by:Dovberman
ID: 39619727
Yes, the StockHist table is queried many times.

How can this be optimized?

Thanks,
0
 

Author Closing Comment

by:Dovberman
ID: 39633554
That worked.

Thanks
0

Featured Post

PRTG Network Monitor: Intuitive Network Monitoring

Network Monitoring is essential to ensure that computer systems and network devices are running. Use PRTG to monitor LANs, servers, websites, applications and devices, bandwidth, virtual environments, remote systems, IoT, and many more. PRTG is easy to set up & use.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

How to leverage one TLS certificate to encrypt Microsoft SQL traffic and Remote Desktop Services, versus creating multiple tickets for the same server.
Ever needed a SQL 2008 Database replicated/mirrored/log shipped on another server but you can't take the downtime inflicted by initial snapshot or disconnect while T-logs are restored or mirror applied? You can use SQL Server Initialize from Backup…
This videos aims to give the viewer a basic demonstration of how a user can query current session information by using the SYS_CONTEXT function
Via a live example, show how to backup a database, simulate a failure backup the tail of the database transaction log and perform the restore.

831 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question