十大和更新

时间:2013-04-25 04:59:57

标签: sql sql-server vb.net visual-studio-2012

如何使用VB运行查询,该查询将根据列appClickCount返回TOP 10结果并将列appFAIList更新为1,而TOP 10以下的任何内容都会使列appFAIList的值为0?

Using sqlCon = New SqlConnection("Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\ITCSDatabase.mdf;Integrated Security=True")
        sqlCon.Open()
        Dim sqlText = "SELECT top 10 appClickCount " & _
            "FROM appTable" & _
        "UPDATE appTable SET appFAIList = 1"
        Dim cmd = New SqlCommand(sqlText, sqlCon)
        cmd.ExecuteScalar()
    End Using

2 个答案:

答案 0 :(得分:3)

改为运行此SQL语句

with t as (
  select *, rn=row_number() over (order by 1/0)
  from appTable)
update t set
  appFAIList = case when rn<=10 then 1 else 0 end

你的 vb.net 代码虽然很麻烦。您正在使用 ExecuteScalar ,它旨在返回单行单列结果。如上所述,它将为您提供第一个appClickCount值。

另一个问题是在SQL Server中使用TOP 10而没有相应的ORDER BY意味着 非常随意 (又名“随机”)返回任何表中的10条记录。

答案 1 :(得分:0)

UPDATE a
SET a.appFAIList = 1
  FROM appTable AS a
  INNER JOIN 
  (SELECT top 10 appClickCount FROM appTable) AS b ON a.SomeField = b.SomeField

SomeField - may be primary key of your table