简体   繁体   English

如何在vb.net中进行动态sql查询?

[英]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 我正在尝试在vb.net中执行此动态sql查询,其中我声明了两个变量并在每个变量上传递一个SELECT

 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 tnx提前

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: 你不能从sqlcommand那样做,所以要执行你的代码,你必须创建一个存储过程并添加到最后:

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? 我假设您正在做一些比您的实际例子更有创意的事情,但无论如何都要在select语句中包含所有内容? A correct version should go something like this: 正确的版本应该是这样的:

Select (select count(*) from table1tbl), (select count(*) from table2tbl) 选择(从table1tbl中选择count(*)),(从table2tbl中选择count(*))

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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