Solved

Append a table from the rows returned by a SQL Statement

Posted on 2013-11-01
6
317 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 3
  • 2
6 Comments
 
LVL 41

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
Three Reasons Why Backup is Strategic

Backup is strategic to your business because your data is strategic to your business. Without backup, your business will fail. This white paper explains why it is vital for you to design and immediately execute a backup strategy to protect 100 percent of your data.

 
LVL 41

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

Get 15 Days FREE Full-Featured Trial

Benefit from a mission critical IT monitoring with Monitis Premium or get it FREE for your entry level monitoring needs.
-Over 200,000 users
-More than 300,000 websites monitored
-Used in 197 countries
-Recommended by 98% of users

Question has a verified solution.

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

International Data Corporation (IDC) prognosticates that before the current the year gets over disbursing on IT framework products to be sent in cloud environs will be $37.1B.
In part one, we reviewed the prerequisites required for installing SQL Server vNext. In this part we will explore how to install Microsoft's SQL Server on Ubuntu 16.04.
Via a live example combined with referencing Books Online, show some of the information that can be extracted from the Catalog Views in SQL Server.
Via a live example, show how to setup several different housekeeping processes for a SQL Server.

632 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