如何从SQL数据库中编写VB.NET中的标量查询?

时间:2011-07-11 00:18:04

标签: sql vb.net

我试图编写VB.NET查询而不编写SQL存储过程。我已经获得了许多数据集文本查询。但是我无法让这个标量查询起作用。我想要做的就是获得这个T-SQL查询的结果。我怎样才能成功编码?

select (DateDiff(w, '1/1/' + '2011', getdate())) / 7 AS SELECTED_WEEK

(此代码的作用是返回当年的当前周)。以上查询是否会将值作为整数数据类型或字符串返回?

我尝试了你的答案,但它给了我这个异常错误:

System.InvalidOperationException: ExecuteReader requires an open and available Connection. The connection's current state is Closed.

你知道这意味着什么吗?

1 个答案:

答案 0 :(得分:1)

Dim result As Integer
Dim sql As String = "select (DateDiff(w, '1/1/' + '2011', getdate())) / 7 AS SELECTED_WEEK"

Using cn As New SqlConnection("your connection string here"), _
      cmd As New SqlCommand(sql, cn)

    cn.Open()
    result = Convert.ToInt32(cmd.ExecuteScalar())
End Using