简体   繁体   中英

How to write a scalar query in VB.NET from a SQL database?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM