在dbCommand.CommandText中逐个命令

时间:2011-10-31 17:25:31

标签: sql vb.net ms-access

我正在尝试在dbcommand.commandtext中添加一个order by case语句,但我发现没有返回任何行。我想在case语句中为颜色分配优先级。这将有助于我避免为优先级创建一个新表,并重写大量代码来映射外键。任何输入都会有所帮助。

以下是声明: -

Protected Sub AddData()
    Dim cn As OleDbConnection = New OleDbConnection(ConfigurationManager.AppSettings("ConnectionString"))
    cn.Open()
    Dim dbCommand As New OleDbCommand
    dbCommand.Connection = cn

    dbCommand.CommandText = "SELECT * from tblPosts ORDER BY CASE PriorityLevel WHEN 'Red' then 1 when 'Orange' then 2 ELSE 3 END"

    Try
        dbCommand.ExecuteNonQuery()
        Dim objdatareader As OleDbDataReader = dbCommand.ExecuteReader()
        While objdatareader.Read()
            Dim PostID As Integer = CInt(objdatareader("ID"))
            PopulateImages(PostID, cn)
            PopulateCategories(PostID, cn)
            rssFeed.AddItem(objdatareader, ImageList, CategoryList)
            ImageList.Clear()
            CategoryList.Clear()
        End While

        objdatareader.Close()
    Catch myerror As OleDbException
        Dim strErr As String = "There was an error updating the database: " & myerror.Message
    End 

谢谢

1 个答案:

答案 0 :(得分:0)

你有任何例外吗?我收到语法错误,因为您有END PriorityLevel。在PriorityLevel之后删除END不会带来任何语法错误。

除此之外,您的陈述看起来是正确的。

这有效:

declare @tblPosts table(
  PriorityLevel varchar(10)
  )

  insert into @tblPosts
  values('Orange'),('Red'),('Green'),('Orange')

  SELECT * from @tblPosts ORDER BY 
  CASE PriorityLevel WHEN 'Red' then 1 
                     when 'Orange' then 2 
  ELSE 3 END 

这不起作用:

declare @tblPosts table(
  PriorityLevel varchar(10)
  )

  insert into @tblPosts
  values('Orange'),('Red'),('Green'),('Orange')

  SELECT * from @tblPosts ORDER BY CASE 
  PriorityLevel WHEN 'Red' then 1 
                when 'Orange' then 2 
  ELSE 3 END PriorityLevel