Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 7070309
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 28, 20262026-05-28T05:33:04+00:00 2026-05-28T05:33:04+00:00

I want to check if a for that loop between a DataTable be faster

  • 0

I want to check if a for that loop between a DataTable be faster or do this operation in SQL Server. So, I create a table like this:

CREATE TABLE [dbo].[tbl_Test_Data](
[Id] [int] IDENTITY(1,1) NOT NULL,
[Name] [nvarchar](50) NOT NULL,
[LName] [nvarchar](50) NOT NULL,
[f_date] [datetime] NOT NULL,
[flag] [bit] NOT NULL,
[Age] [int] NOT NULL,
[amount] [decimal](23, 5) NOT NULL,
   CONSTRAINT [PK_tbl_Test_Data] PRIMARY KEY CLUSTERED ([Id] ASC)

and then I create an index on the Age column:

CREATE NONCLUSTERED INDEX [idx_age] ON [dbo].[tbl_Test_Data] 
(
[Age] ASC
)
INCLUDE ( [Id], [f_date]) 

and insert 100000 rows of test data:

DECLARE @a   INT
SET @a = 100000;

WHILE @a >= 0 
BEGIN
DECLARE @d DATETIME ;
SET @d = DATEADD(d,CAST(RAND() * 100 AS INT),GETDATE());

DECLARE @b BIT;
IF @a % 2 =0
    SET @b=0;
ELSE
    SET @b=1;

    INSERT INTO tbl_Test_data
    VALUES(N'nima',
           N'agha',
           DATEADD(d,CAST(RAND() * 100 AS INT),GETDATE()),
           @b,
           CAST(RAND() * 100 AS INT),
           CAST(RAND()  AS DECIMAL(23,5)) )

SET @a=@a -1;
END

Then I create a C# windows application with 2 buttons. For update from sql query I write this code:

private void button2_Click(object sender, EventArgs e)
{
   Stopwatch sq = new Stopwatch();
   sq.Start();

   using (SqlConnection cn = new SqlConnection("Data Source=.;Initial Catalog=Northwind;Integrated Security=True"))
   {
       using (SqlCommand cmd = new SqlCommand())
       {
           string txt = "UPDATE tbl_Test_Data SET f_date=getdate() WHERE Age>80;";
           txt += "SELECT Id,Name,LName,f_date,flag,Age,amount FROM [Northwind].[dbo].[tbl_Test_Data]";
           cmd.CommandText = txt;
           cmd.CommandType = CommandType.Text;
           cmd.Connection = cn;

           using (SqlDataAdapter da = new SqlDataAdapter())
           {
               da.SelectCommand = cmd;
               DataTable dt = new DataTable();
               cn.Open();
               da.Fill(dt);
               cn.Close();

               dataGridView2.DataSource = dt;
           }
        }
   }
   sq.Stop();
   label2.Text = sq.Elapsed.TotalMilliseconds.ToString();
}

and for using for loop I write this:

 Stopwatch sq = new Stopwatch();
 sq.Start();
 using (SqlConnection cn = new SqlConnection("Data Source=.;Initial Catalog=Northwind;Integrated Security=True"))
 {
    using (SqlCommand cmd = new SqlCommand())
    {
       cmd.CommandText = "SELECT Id,Name,LName,f_date,flag,Age,amount FROM [Northwind].[dbo].[tbl_Test_Data]";
       cmd.CommandType = CommandType.Text;
       cmd.Connection = cn;

       using (SqlDataAdapter da = new SqlDataAdapter())
       {
          da.SelectCommand = cmd;
          DataTable dt = new DataTable();
          cn.Open();
          da.Fill(dt);
          cn.Close();

          for (int i = 0; i < dt.Rows.Count; i++)
          {
             if (int.Parse(dt.Rows[i]["Age"].ToString()) > 80)
             {
                dt.Rows[i]["f_date"] = DateTime.Now;
             }
             else
             {
                dt.Rows[i]["f_date"] = DateTime.Now.AddDays(-100);
             }
          }

          dataGridView1.DataSource = dt;
       }
   }
}
sq.Stop();
label1.Text = sq.Elapsed.TotalMilliseconds.ToString();

but I see surprisingly that when I use for loop it takes shorter time than SQL Server. About(50%). I test it several times.

Why using for take shorter time that using an update?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-28T05:33:04+00:00Added an answer on May 28, 2026 at 5:33 am

    The UPDATE actually has to deal with locks and disk access at the server level, and it also has to update your indexes on the base table.

    The for loop doesn’t have to deal with any of this overhead. However, changes made in the for loop are not visible to anything else besides your application.

    The UPDATE would make the change for all other queries to that table. The for loop changes are only visible within the application scope with the data table.

    As an aside, it’s also possible that if you ran these queries in the order they are in posted, that the first query paid the IO cost to retrieve the pages from disk, and the second run was able to pull the cached pages from memory.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

how i can check in this code that the parent in loop is span
I have check boxes I want to have a for loop that it will
I want to check that a file system path is valid and safe to
I want to check that some integer type belongs to (an) enumeration member. For
Before Entering data into a database, I just want to check that the database
I have a whole bunch of mavenised projects, and I want to check that
I want to compare two ms-access .mdb files to check that the data they
I have used checkbox column in gridview. I want to check status of that
I want to check my database for records that I already have recorded before
I want to check when the user double click on applictaion icon that no

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.