如何从 SQL 数据库在 VB.NET 中编写标量查询? [英] How to write a scalar query in VB.NET from a SQL database?

查看:21
本文介绍了如何从 SQL 数据库在 VB.NET 中编写标量查询?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试编写 VB.NET 查询而不编写 SQL 存储过程.我已经得到了许多数据集文本查询的工作.但是我在让这个标量查询工作时遇到了麻烦.我想要做的就是获得这个 T-SQL 查询的结果.我怎样才能成功编码?

I am trying to write VB.NET query without writing SQL stored procs. I have already gotten many dataset text queries to work. But I am having trouble with getting this scalar query to work. All I want to do is to get the result of this T-SQL query. How can I code this successfully?

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

(此代码的作用是返回一年中的当前周).上面的查询会以整数数据类型还是字符串形式返回值?

(What this code does is it returns the current week of the year). And will this query above return the value as an integer datatype or string?

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

I tried your answers but it gave me this exception error:

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

你知道这是什么意思吗?

Do you know what this means?

推荐答案

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

这篇关于如何从 SQL 数据库在 VB.NET 中编写标量查询?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆