简体   繁体   中英

how to do dynamic sql query in vb.net?

i'm trying to do this dynamic sql query in vb.net where i declare two variable and pass a SELECT on each variable

 Dim cmd As New SqlCommand("Declare @val1 int " & _
                           "Declare @val2 int " & _
                           "SET @val1 = 'SELECT Count(*) from table1tbl'" & _
                           "SET @val2 = 'SELECT Count(*) from table2tbl'", conn)
    Dim rdr As SqlDataReader = cmd.ExecuteReader
    rdr.Read()
    Dim str1 = rdr("@val1")
    Dim str2 = rdr("@val2")
    rdr.Close()

i know this code is not right..so how to makes this right ? tnx in advance

You can't do that from a sqlcommand, so to execute your code you'd have to create a stored procedure and add to the end:

Select @val1, @val2

To return the values as a table that you are creating.

I assume that you are doing something more creative than your actual example, but is there anyway of including everything in your select statement? A correct version should go something like this:

Select (select count(*) from table1tbl), (select count(*) from table2tbl)

That will return the data in the format you want so that you can read it with the code you have posted.

Dim sQuery as String
Dim val1 
Squery = <a> SELECT Count(*) from table1tbl </a>.Value
Using cmd As New SqlCommand(sQuery, con)
  If cmd.Connection.State <> ConnectionState.Open Then
    cmd.Connection.Open()
  End If
val1 = 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