Following code is not returning any results:
search = "'%" & Request.QueryString("itemname") & "%'"
Set cmd = Server.CreateObject("ADODB.COMMAND")
Set cmd.ActiveConnection = conn
sql = ""
sql = sql & "DECLARE #search varchar;"
sql = sql & "SET #search = ?;"
sql = sql & "SELECT ID, itemname, itemtype FROM vw_items WHERE itemname LIKE #search"
cmd.CommandText = sql
cmd.CommandType = adCmdText
response.write("<strong>You searched for:</strong> " & search & "<br /><br
/>")
cmd.Parameters.Append cmd.CreateParameter("#search", adVarchar, adParamInput, 50, search)
set rs = cmd.Execute
else
search = null
strSQL2 = "SELECT * FROM vw_items"
set rs = server.CreateObject("ADODB.Recordset")
rs.open strSQL2,conn
end if
I've seen this answer: ADO parameterised query not returning any result and tried fixing mine but no luck
Any help would be much appreciated
When using ADODB.Command the provider infers the data type based off the Parameters collection that is setup before calling the Execute() method.
As you are passing in as
search = "'%" & Request.QueryString("itemname") & "%'"
in effect when the SQL is executed by the provider it will look like (because it already knows the Parameter is a VARCHAR data type already)
WHERE itemname LIKE ''%youritemname%''
When you actually want it to be
WHERE itemname LIKE '%youritemname%'
This means the current query is doing a LIKE for the physical string '%youritemname%' rather than doing an actually pattern matching query.
The fix is simple, remove the single quotes from the search variable, like so;
search = "%" & Request.QueryString("itemname") & "%"
Useful Links
A: How to use ASP variables in SQL statement (useful tips when working with the ADODB.Command object)
Related
I have a working query in Access to linked SQL Server tables that I pass user input to using
WHERE (RIGHT(dbo.qryrptWhereUsed.ITEM, 9)=[INPUT_PROMPT:])
I would like to continue using Access to store similar simple queries that require user input but want to do this via a passthru query directly to the SQL Server db thus eliminating the mirrored tables in Access.
How do I accomplish this?
You can use the following code:
Dim strPrompt As String
strPrompt = InputBox("Enter where used >")
With CurrentDb.QueryDefs("qryPass")
.SQL = "select * from dbo.qryWhereUsed where ITEM = '" & strPrompt & "'"
.Execute
End With
If you running a report, then just go:
Dim strPrompt As String
strPrompt = InputBox("Enter where used >")
With CurrentDb.QueryDefs("qryPass")
.SQL = "select * from dbo.qryWhereUsed where ITEM = '" & strPrompt & "'"
End With
DoCmd.OpenReport "myreport", acViewPreview
I've been searching hard the past few days and have come across numerous examples that outline what I'm trying to do. However, I can't seem to get this working. I have a combobox that populates data (a company name) from a table when the form initializes. I then want to take the value chosen in the combo box and run another query to cross reference an id number in that same table.
Private Sub CommandButton1_Click()
Dim myCn As MyServer
Set myCn = New MyServer
Dim rs As ADODB.recordset
Set rs = New ADODB.recordset
Dim sqlStr As String
Dim CompField As String
'CompField = ComboBox1.Value
sqlStr = "SELECT DISTINCT [acctno] FROM client WHERE [company] = '" & ComboBox1.Text & "'"
'sqlStr = "Select DISTINCT [company] FROM client;"
' sqlStr = "SELECT DISTINCT [acctno] FROM client WHERE [company] = " & UserForm1.ComboBox1.Value & ";"
'sqlStr = "SELECT DISTINCT [acctno] FROM client WHERE [company] = " & UserForm1.ComboBox1.Text & ";"
'sqlStr = "SELECT DISTINCT [acctno] FROM client WHERE [company] = 'Company XYZ';"
'sqlStr = "SELECT DISTINCT [acctno] FROM client WHERE company = " & CompField & ""
rs.Open sqlStr, myCn.GetConnection, adLockOptimistic, adCmdText
MsgBox sqlStr
'MsgBox ComboBox1.Value
'MsgBox rs(0)
rs.Close
myCn.Shutdown
Set rs = Nothing
Set myCn = Nothing
End Sub
Currently with the combobox value encased in single quotes i get the entire sql string returned. If I remove the single quotes I get a syntax error referencing part of the combobox value. All other efforts have resulted in run-time errors that have led me nowhere.
I know my query works because I've tested it in SQL Studio and if I hard code a text value in this code I also get the Account ID I'm looking for. Not sure what I'm missing here.
Well I figured it out. I was expecting to be able to MsgBox the variable assigned to the SQL query and see my results. But it doesn't work that way. I had to use ADO GetString method for that and assign another variable. Oh and you were right about escaping, I had to add delimters to properly handle the ComboBox value in the query which ultimately looked like this
sqlStr = "SELECT DISTINCT [acct_no] FROM client WHERE [company] = " & Chr(39) & Me.ComboBox1.Value & Chr(39)
Thanks for your help on this
I use external data from an SQL query in excel to pull data onto a spreadsheet then the spreadsheet can be sent to one of my colleges in say the sales department and they can view the queried information.
I want to be able to have a cell that they can enter data into and press a refresh button.
So I need to do some thing like this:
SELECT Customer.CustomerCode, Customer.Name,
OrderHeader.OrderType, OrderHeader.OrderNumber
FROM Customer INNER JOIN
OrderHeader ON Customer.CustomerID = OrderHeader.CustomerID
WHERE (OrderHeader.OrderType = 2) AND (OrderHeader.OrderNumber = Range("A1").Value)
Not sure how or if this is possible and the reason I need to do this is because i'm going through lines from all the Quotes and if there is over 65536 then i'll have a problem.
This is what I have at the moment the SQL is different but that doesn't matter
The easiest way is to pull the values for the parameters into VBA, and then create the SQL statement as a string with the parameter values, and then populate the commandtext of the query.
Below is a basic example of the parameter in cell A1.
Sub RefreshQuery()
Dim OrderNo As String
Dim Sql As String
' Gets value from A1
OrderNo = Sheets("Sheet1").Range("A1").Value
'Creates SQL Statement
Sql = "SELECT Customer.CustomerCode, Customer.Name, " & _
"OrderHeader.OrderType , OrderHeader.OrderNumber " & _
"FROM Customer " & _
"INNER Join OrderHeader ON Customer.CustomerID = OrderHeader.CustomerID " & _
"WHERE (OrderHeader.OrderType = 2) And (OrderHeader.OrderNumber = " & OrderNo & ") "
With ActiveWorkbook.Connections(1).ODBCConnection
.CommandText = Sql
.Refresh
End With
End Sub
This assumes you have the query in Excel to begin with, and that it's the only query. Otherwise you'll have to define the name of the query as below:
With ActiveWorkbook.Connections("SalesQuery").ODBCConnection
I hope that helps :)
Further to #OWSam's example using ODBC, we can also use ADO to pull back query results from SQL Server. Using ADO, you cannot use windows verification and you will need the user to input their password somehow, to be able to run the query.
Personally I create a userform which has UserName and Password. Username pre-populated using Environ, and then they can type their password into the relevant TextBox.
Sub sqlQuery()
Dim rsConn As ADODB.Connection, rsData As ADODB.Recordset
Dim strSQL As String, winUserName As String, pwd As String
winUserName = UCase(Environ("username"))
pwd = "mypassword" 'password needed here.
strSQL = "SELECT * FROM mydatabase" 'query
Set rsConn = New ADODB.Connection
With rsConn
.ConnectionString = "Provider = sqloledb;" & _
"Data Source = [server name here];" & _
"Initial Catalog = [initial database];" & _
"Integrated Security=SSPI;" & _
"User ID = " & winUserName & ";" & _
"Password = " & pwd & ";"
.Open
End With
Set rsData = rsConn.Execute(strSQL)
Range("A1").CopyFromRecordset rsData
End Sub
Edit: You must go into references and turn on the Microsoft ActiveX Data Objects Recordset 6.0 library (or equivalent within your VBE).
I have an SQL update command that I can't get to work. i want it to update the fields where the date is equal to the current date. It works for my INSERT and SELECT statements. But I get a missing operator error when using it for my Delete statement below.
Cmd.Connection = conn
Cmd.CommandText = "UPDATE tbl_Expenditure SET E_Stock =" & NewEStock & "," & "E_Total =" & ETotal & "WHERE [E_Date] = #" & thisMonth & "/" & Day & "/" & thisYear & "#;"
Cmd.ExecuteNonQuery()
Ive tried searching this site as well as others and can't seem to find an answer.
This is my error
Syntax error (missing operator) in query expression '95WHERE [E_Date] = #4/1/2015#'.
Thanks for any help
Using conn As New SqlConnection("connection string here"), _
cmd As New SqlCommand("UPDATE tbl_Expenditure SET E_Stock = #Stock, E_Total = #Total WHERE [E_Date] = #Date;", conn)
'Guessing at column types here
cmd.Parameters.Add("#Stock", SqlDbType.Int).Value = NewEStock
cmd.Parameters.Add("#Total", SqlDbType.Decimal, 8, 2).Value = ETotal
cmd.Parameters.Add("#Date", SqlDbType.DateTime).Value = New DateTime(thisYear, thisMonth, Day)
cmd.ExecuteNonQuery()
End Using
This fixes a HUGE security issue in the code, it has a performance benefit in allowing Sql Server to cache your query plan, and it solves your problem in that is makes it much easier to spot silly syntax mistakes like the missing space in front of the WHERE clause.
I am using SQL 2005 as backend and MS Access as frontend.
Now, I get all my filtering of the data with views and no problems so far but I came accross some issues.
In access I had a form and on that form I had a field1 which I used to filter the data I wanted in that form with query. Example: Last, First Name or DOB. In Access I used the Expression builder to point the query to that field and I got my filter.
Now how do I do it in this new environment since when I create view (In Access) I can not filter on that field.
I was thinking on sp but I am not sure how do i go about it.
Any ideas?
I was thinking on sp but I am not sure how do i go about it.
If you still wanted to keep this form a normal “bound” access form then you could do something like this.
Setup a pass through query that fires your SP. The basic format for that is along the lines of this
EXEC [dbo].[spAgents_with_more_than_X_days_sick_by_Team] #Date_from = N'2009-09-14', #Date_to = N'2010-09-14', #Team_ID = N'TEM1', #Days_sick =5
You would then modify this when opening the form like this
Set qDef = DBEngine(0)(0).QueryDefs("RqryAgents_more_than_X_sicks_detail_2")
With qDef
.Connect = strSQL_con_string
.SQL = "EXEC [dbo].[spAgents_with_more_than_X_days_sick_by_Team]"
.SQL = .SQL & " #Date_from = N'" & Format(Me.txtDate_from, "yyyy-mm-dd") & "', "
.SQL = .SQL & "#Date_to = N'" & Format(Me.txtDate_to, "yyyy-mm-dd") & "', "
.SQL = .SQL & "#Team_ID = N'" & Me.txtTeam_ID & "', "
.SQL = .SQL & "#Days_sick =" & Me.txtDays_sick
End With
This should work just fine however if it was me (and I know it’s not everyone’s preference) but I would make this an unbound form and populate it by firing your SP using ADO to fill a recordset and go from there.
If you want details of how to do that then just ask and I will post an example
EDIT: Code sample added
Dim cmd as new ADODB.Command
Dim dbCon as new ADODB.Connection
Dim rst as new ADODB.Recordset
dbCon.ConnectionString=”Your_Connection_string”
dbCon.open
With cmd
.ActiveConnection = dbCon
.CommandText = "spYour SP"
.CommandType = adCmdStoredProc
.NamedParameters = True
.Parameters.Append .CreateParameter("#Your_pram1", adVarChar, adParamInput, 20, Format(Me.txtDate, "yyyy-mm-dd"))
.Parameters.Append .CreateParameter("#Your_pram2", adSmallInt, adParamInput, 0, Me.cboPhone_skill)
End With
Set rst = cmd.Execute()
With rst
If .EOF=False then
Me.txtYour_text_box_1=!Your_SP_field_1
Me.txtYour_text_box_2=!Your_SP_field_3
Me.txtYour_text_box_3=!Your_SP_field_2
End if
End with
Rst.close
Dbcon.close
Set rst=nothing
Set cmd=nothing
Set dbcon=nothing
You don't mention if these text boxes are in fact in the same form with the data and you don't mention if each text box was optional, and if they were not optional, then did you fill out 1, 2 or 3 boxes and then hit a button?
If you just looking to find people with a given lastName, then in the after update event of the un bound lastname box, just go:
Me.RecordSource = "select * from tblCustomers where LastName = '" & me.txtLastName "'"
The above is one line of code. I just don't see the need for so much code as others posted here.
You can expand on your question if you looking to make all 3 boxes optional, or if you looking to have a search based on more then one box, but I can rather tell you that you don't need the amounts of code posted here, but the one line of code as per above will suffice.