1

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

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

Comments

1
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

2 Comments

what's with that <a> tag thing ?
'its a Multy line string ex: Dim var1 As String var1 = "ABC" Dim str = <a> Hello it's the first line And you can do this <%= var1 %> </a>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.