使用循环更新SQL Server表的每个现有行

时间:2017-01-04 13:43:16

标签: c# asp.net sql-server

我尝试使用ASP.NET,C#为SQL Server表中的每一行更新某个列。

当执行此代码时,我希望列中第一行的OrderNo为= 1.从那时起,我希望OrderNo对表中的其他现有行递增1。

目前,我可以更新一行的OrderNo,但是我无法通过循环来正确读取所有行和&按照我的意愿增加。

这是我表格的结构

Here

以下是我的C#:

 con.Open();
 SqlCommand cmdUpdateOrderNo;
 cmdUpdateOrderNo = new SqlCommand("UPDATE tblImages SET [OrderNo]=@O WHERE [OrderNo] = 2;", con);
 cmdUpdateOrderNo.Parameters.AddWithValue("@O", 4);
 cmdUpdateOrderNo.ExecuteNonQuery();

以下是我需要更新OrderNo的原因:

  protected void Timer1_Tick(object sender, EventArgs e)
{
    int i = (int)ViewState["ImageDisplayed"];
    i = i + 1;
    ViewState["ImageDisplayed"] = i;
    DataRow imageDataRow = ((DataSet)ViewState["ImageData"]).Tables["image"].Select().FirstOrDefault(x => x["order"].ToString() == i.ToString());
    if (imageDataRow != null)
    {
        Image1.ImageUrl = "~/MyImages/" + imageDataRow["name"].ToString();
        lblImageName.Text = imageDataRow["name"].ToString();
        lblImageOrder.Text = imageDataRow["order"].ToString();
        lblImageDesc.Text = imageDataRow["Desc"].ToString();
    }
    else
    {
        SetImageUrl();
    }
}

private void SetImageUrl()
{
    DataSet ds = new DataSet();//Creating a dataset
    SqlDataAdapter da = new SqlDataAdapter("SELECT Name, [Order], [Desc] FROM tblImages", con);
    da.Fill(ds, "image");

    ViewState["ImageData"] = ds;//storing the dataset in a ViewState variable
    ViewState["ImageDisplayed"] = 1;//storing order number of the image currently displayed

    DataRow imageDataRow = ds.Tables["image"].Select().FirstOrDefault(x => x["order"].ToString() == "1");
    Image1.ImageUrl = "~/MyImages/" + imageDataRow["name"].ToString();
    lblImageName.Text = imageDataRow["name"].ToString();
    lblImageOrder.Text = imageDataRow["order"].ToString();
    lblImageDesc.Text = imageDataRow["Desc"].ToString();
}

2 个答案:

答案 0 :(得分:3)

我同意@Jamiec的观点,这似乎是一个坏主意,但如果它真的是你想做的话,你不需要循环。这是使用CTE和窗口函数的示例。

示例

WITH T AS
    (   SELECT  
            *,
            ROW_NUMBER() OVER (ORDER BY ID) as RN
        FROM    YourTable
    )

/* this shows you the results of the CTE, 
   specifically the ROW_NUMBER() 
   which will replace the OrderNo in the code below */

SELECT * FROM T 

运行此更新表

WITH T AS
(   SELECT  
        *,
        ROW_NUMBER() OVER (ORDER BY ID) as RN
    FROM    YourTable
)
UPDATE T
SET OrderNo = RN

答案 1 :(得分:-1)

在处理SQL时,你几乎不想写循环。

尝试将命令更改为此

; with cte as
(
    select *, row_number() over (order by ID) as rn 
    from tblImages
) 
update tblImages
set OrderNo = rn
from cte