Expiring Today—Celebrate National IT Professionals Day with 3 months of free Premium Membership. Use Code ITDAY17

x
?
Solved

Append a table from the rows returned by a SQL Statement

Posted on 2013-11-01
6
Medium Priority
?
326 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 1000 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 1000 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
Prepare for your VMware VCP6-DCV exam.

Josh Coen and Jason Langer have prepared the latest edition of VCP study guide. Both authors have been working in the IT field for more than a decade, and both hold VMware certifications. This 163-page guide covers all 10 of the exam blueprint sections.

 
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

Will your db performance match your db growth?

In Percona’s white paper “Performance at Scale: Keeping Your Database on Its Toes,” we take a high-level approach to what you need to think about when planning for database scalability.

Question has a verified solution.

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

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 article shows gives you an overview on SQL Server 2016 row level security. You will also get to know the usages of row-level-security and how it works
Via a live example, show how to extract information from SQL Server on Database, Connection and Server properties
Viewers will learn how to use the SELECT statement in SQL and will be exposed to the many uses the SELECT statement has.

719 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