我最近一直试图找到一种方法来让参数化查询起作用,我想我差不多了但是在执行查询时似乎遇到了错误
这是代码
Dim LogData2 As sterm.MarkData = New sterm.MarkData()
Dim query As String = ("Select * from openquery (db, 'SELECT * FROM table WHERE investor=@investor')")
Dim cmd As New SqlCommand(query)
cmd.Parameters.AddWithValue("@investor", 34)
Dim drCode2a As DataSet = LogData2.StermQ3(query)
我已经调试了它,似乎没有将参数放入查询中。
"Select * from openquery (db, 'SELECT * FROM table WHERE investor=@investor')"
这是我调试行Dim drCode2a As DataSet = LogData2.StermQ3(query)
任何想法我做错了什么?
解
以下是我解决问题的方法
Dim conn As SqlConnection = New SqlConnection("server='h'; user id='w'; password='w'; database='w'; pooling='false'")
conn.Open()
Dim query As New SqlCommand("DECLARE @investor varchar(10), @sql varchar(1000) Select @investor = 69836 select @sql = 'SELECT * FROM OPENQUERY(db,''SELECT * FROM table WHERE investor = ''''' + @investor + ''''''')' EXEC(@sql)", conn)
dgBookings.DataSource = query.ExecuteReader
dgBookings.DataBind()
感谢您的帮助
答案 0 :(得分:1)
Ok Jamie taylor我会再次尝试回答你的问题。
您正在使用OpenQuery,因为您可能正在使用链接数据库
基本上问题是OpenQuery方法接受一个字符串,你不能将变量作为发送给OpenQuery的字符串的一部分传递。
您可以像这样格式化查询。表示法遵循servername.databasename.schemaname.tablename。如果您通过odbc使用链接服务器,则省略databasename和schemaname,如下所示
Dim conn As SqlConnection = New SqlConnection("your SQL Connection String")
Dim cmd As SqlCommand = conn.CreateCommand()
cmd.CommandText = "Select * db...table where investor = @investor"
Dim parameter As SqlParameter = cmd.CreateParameter()
parameter.DbType = SqlDbType.Int
parameter.ParameterName = "@investor"
parameter.Direction = ParameterDirection.Input
parameter.Value = 34