I have this VB script that is being ran inside a 3rd party app and is throwing the "Expected End of Statement' Error. Here is the code in question. The select statment works fine in SQL server manager studio.
Thanks.
Dim SecurityDB
Set SecurityDB = CreateObject("ADODB.Connection")
Conn = "DRIVER={SQL Server};SERVER=ustcca015s6\Continuum;DATABASE=continuumdb;UID=Andy8796;PWD=xxxx1234;"
SecurityDB.Open Conn
Set EmployeeRS = SecurityDB.Execute "Select count(*) from dbo.personnel where state=1 and lastname not like 'lapt%' and lastname is not NULL and valuelo in (Select ObjectIdLo from area where uiname like 'usmm%' and uiname not like '%gate%') and valuelo <> 1111497912;"
Result = EmployeeRS.GetRows
EmployeeRS.Close
SecurityDB.Close
#RichardTheKiwi posted the answer in the comments section two weeks ago but sadly hasn't added it as an answer in the ... answer section. OK, the Point Pimp[ette] is back tonight, so these questions show up as one step closer to "solved"!
Don't you need a bracket after Execute?
Set EmployeeRS = SecurityDB.Execute("Select count(*) from dbo.personnel where state=1 and lastname not like 'lapt%' and lastname is not NULL and valuelo in (Select ObjectIdLo from area where uiname like 'usmm%' and uiname not like '%gate%') and valuelo <> 1111497912;")
Related
I'm trying to get the result of a Count query. I need to know if it's greater than 0.
My code:
Set db = CurrentDb
Set qdg = db.QueryDefs("quyGpSumReportCount")
qdg.Sql = Replace(qdg.Sql, "plugtable", VigilTable)
qdg.Sql = Replace(qdg.Sql, "plugchurch", "'" & vChurch & "'")
Set rst = qdg.OpenRecordset("quyGpSumReportCount")
Debug.Print "Total = " & rst!Total
PartCnt = rst!Total
rst.Close
Set rst = Nothing
The query looks like this for the first church once the replacements have been made:
SELECT Count(*) AS Total
FROM (SELECT DISTINCT t.fldUserID, v.[fldChurch/Parish] FROM tblSpring2022 _
AS t INNER JOIN tblVolunteers AS v ON t.[fldUserID] = v.[ID] WHERE _
(v.[fldChurch/Parish] = '1548 Heights')) AS [%$###_Alias];
Since I don't change back to the query after running it, I can switch to the Datasheet view and see the results. In the Field Totals, there is one entry and it's value is 1. (I've run it with a couple of different churches and get different but accurate values, including 0 for a few.)
Every attempt I've made to capture the value, using the name of the field, Total, or Fields(0) or rst.Fields(0) or anything else comes up Null.
So the query is running and returning the correct result but am unable to access that result from within VBA.
OK, I didn't solve this, you guys did; but it is solved.
For reasons that entirely escape me, qdg.OpenRecordset and qdf.OpenRecordset both resulted in a Data Conversion Error. But db.OpenRecordset, suggested above, works perfectly. Not only does it run but the result of the query finds its way both into a MsgBox and into the textbox on the form, making it possible for me to use it.
If I could upvote comments I would; the solution is, after all, there.
Thanks to all!
I am trying to make the same sql SELECT for every row.
But, I get a problem in the 'showReader = sqlShowSol.ExecuteReader();'
It says - "Syntax error in query. Incomplete query clause."
Why is it?
-- connection was established before. --
System.Data.OleDb.OleDbCommand sqlShowSol = new System.Data.OleDb.OleDbCommand();
sqlShowSol.Connection = connection;
System.Data.OleDb.OleDbDataReader showReader;
int row = 1;
while (true)
{
sqlShowSol.CommandText = "SELECT Q_A,Content FROM #userName WHERE id = #id;";
sqlShowSol.Parameters.AddWithValue("#userName", userName);
sqlShowSol.Parameters.AddWithValue("#id", row);
showReader = sqlShowSol.ExecuteReader();
|-----------------------------------------------------------------------------------------|
There is more code afterwords...
But I get the problem in the last line I typed here.
Tnx 4 help,
Etay
When you write this:
"SELECT Q_A,Content FROM #userName WHERE id = #id;";
You are using a paramater incorrectly. You are not permitted to use a parameter as the table name. The database engine cannot interpret the #userName reference.
I'm creating a Voting System. so it's like this every time A Button1 is pressed + 1 or it will increase the vote in the Access database. I can't find anything in Google.
trx = "update [Table1] SET [Vote] = Vote + 1, (WHERE ID = 1)"
Don't include a comma before the WHERE clause. Also you don't need to put the WHERE clause inside parentheses.
Test this as a new query in the Access query designer.
update [Table1] SET [Vote] = Vote + 1 WHERE ID = 1
Fine tune as needed. And once you have it working in the query designer, adapt your VBA code to use that working statement.
Remove comma before Where and brackets around where clause
trx = "update [Table1] SET [Vote] = Vote + 1 WHERE ID = 1"
I'm a little in need of your help
In my web application I have this Select statement, but once I run it, it retrieves 0 data but when I try my Select statement in the database it has data in it, and my Select statement is correct, by the way my application is already published in the server.
Here's my code
string SelectStatement = "SELECT DATEDIFF(day, kg1653, GETDATE()) datenum, kg1635, (CASE WHEN kg1637 is null THEN 0 END) eis ";
string FromStatement = "FROM hsi.keygroupdata503 ";
string WhereStatement = "WHERE kg1235='" + _securityCode + "' and kg1241 is null";
_sqlDT = ConnectToDatabase(SelectStatement + FromStatement + WhereStatement);
and here's my connection string
System.Data.Odbc.OdbcConnection _odbcConn = new System.Data.Odbc.OdbcConnection();
_odbcConn.ConnectionString = "MY DATABASE CONNECTION STRING";
System.Data.Odbc.OdbcDataAdapter _odbcA = new System.Data.Odbc.OdbcDataAdapter(sqlQuery1, _odbcConn);
DataTable _odbcDt = new DataTable();
_odbcA.Fill(_odbcDt);
return _odbcDt;
Can somebody please help me with this?
Thank you so much!
When does sqlQuery1 get set to _sqlDT ... your best bet is to debug and see what the query is right on the line of it being called and copy it to run on the SQL server in case something else is updating it or _scurityCode is empty. Also if you have a test environment with similar table names, make sure you are connecting to the same live instance.
Side note, not foolproof but make sure _securityCode has a replace statement and change all single quotes to double quotes to work against SQL injection as the commentor above said.
I am encountering a strange problem when attempting to execute a DELETE query agains a SQL Server table using VB.NET, SQL Command, and Parameters.
I have the following code:
Try
sqlCommand.Transaction = transaction1
sqlCommand.Connection = conn
sqlCommand.CommandText = sqlQuery
sqlCommand.Parameters.Add("#userID", SqlDbType.Int).Value = Convert.ToInt32(userID)
sqlCommand.Parameters.Add("#groupID", SqlDbType.Int).Value = Convert.ToInt32(groupID)
''#Delete the user from the group.
MessageBox.Show("User: " + Convert.ToString(userID) + " Group: " + Convert.ToString(groupID))
MessageBox.Show("Param, UserID: " + sqlCommand.Parameters.Item(0).Value.ToString)
MessageBox.Show("Param, GroupID: " + sqlCommand.Parameters.Item(1).Value.ToString)
return_deleteUser = sqlCommand.ExecuteNonQuery()
Catch ex As Exception
transaction1.Rollback()
Dim hr As Integer = Marshal.GetHRForException(ex)
MsgBox("Removal of user from group has failed: " + ex.Message() & hr)
End Try
Which executes the following SQL Query:
Dim sqlQuery As String = "DELETE FROM MHGROUP.GROUPMEMS WHERE USERNUM =#userID AND GROUPNUM =#groupID"
My problem is that when the code executes, there is no error reported at all. I have ran SQL Profiler and the query doesn't appear in the trace list. The three messageboxes that I have added all return the correct values, and if I was to execute the SQL query against the table with the values the query succeeds. Both the userID and groupID are 3-digit integers.
Can anyone suggest why the code is not working as intended, or any further debugging that I can use to step through the code? Ideally I would love to see the completed SQL query with the parameters completed, but I haven't found out how to do this.
EDIT:
I have the following later in the code to check if the execute's all processed successfully:
If return_insertEvent > 0 And return_updateUser > 0 And return_nextSID > 0 And return_deleteUser > 0 Then
MessageBox.Show("Success")
return_removeADGroup = RemoveUserFromGroup(userID, groupName)
MessageBox.Show("Remove FS User from AD Group: " + return_removeADGroup)
transaction1.Commit()
transaction2.Commit()
transaction3.Commit()
transaction4.Commit()
returnResult = 1
Else
transaction1.Rollback()
transaction2.Rollback()
transaction3.Rollback()
transaction4.Rollback()
returnResult = 0
End If
If you require any further information please don't hesitate in contacting me.
You are missing a Transaction.Commit
Update in respone to additional info added to question:
Why do you have 4 transactions? Since their commit and rollbacks are all executed together, you only need one transaction. I suggest you use a TransactionScope
You can assign the current transaction to ADO.NET Command objects:
ADO.NET and System.Transactions
Transaction Processing in ADO.NET 2.0
I might guess that your calling proc has the values of userid and groupid backwards. If the DELETE doesn't find a matching record, it will complete successfully, but not do anything. I suggest wrapping your delete up in a stored procedure. Then you can add code to test if the parameter values are getting through correctly.
Create Procedure UserDelete
#userid int, #groupID int
As
BEGIN
Select #userid as UID, #groupID as GID INTO TESTTABLE;
DELETE FROM MHGROUP.GROUPMEMS WHERE USERNUM =#userID AND GROUPNUM =#groupID;
END
Run your code then go check the contents of TESTTABLE.
FWIW: I don't like trying to get the whole parameter declaration in one line. Too much going on for me. I like this...
Dim pUID as New Parameter("#userid", SqlDbType.Int)
pUID.Value = userid
cmd.Parameters.Add(pUID)
After some time debugging and sql tracing, I have found out that the stupid application that the DB belongs to treats the group members differently, the groups reside in a administration database, but the users membership to the group resides in another database.
Thank you to everyone above who provided there time and thoughts in assisting with the code. I have changed the code as recomended to use only two transactions and two connections (1 for the admin and sub-database). The code is much nicer now and is that bit easier to read.
Thanks again,
Matt